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

function parseJenis(value: string | null): FilterJenisCatatan {
	if (value === 'pendapatan' || value === 'pengeluaran') return value;
	return 'semua';
}

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

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

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

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