import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { getLaporanPenjualanByDate } from '$lib/server/laporan-detail';
import { getWarungByMemberId } from '$lib/server/warung';
import { parseLaporanDateRange } from '$lib/utils/laporan-date';

export const load: PageServerLoad = async ({ locals, url, depends }) => {
	depends('laporan:penjualan');

	if (!locals.member) {
		throw redirect(303, '/login');
	}

	const { tanggalAwal, tanggalAkhir } = parseLaporanDateRange(
		url.searchParams.get('dari'),
		url.searchParams.get('sampai')
	);
	const warung = await getWarungByMemberId(locals.member.id);
	const laporan = await getLaporanPenjualanByDate(
		locals.member.id,
		tanggalAwal,
		tanggalAkhir,
		locals.member.nama,
		warung?.nama ?? 'Warung'
	);

	return {
		member: locals.member,
		laporan
	};
};
