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

function parseFilter(value: string | null): FilterHutangPiutang {
	if (value === 'hutang' || value === 'piutang' || value === 'belum_lunas') return value;
	return 'semua';
}

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

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

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

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