import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { getLaporanData } from '$lib/server/laporan';
import { getWarungByMemberId } from '$lib/server/warung';
import type { PeriodeLaporan } from '$lib/types/laporan';

function parsePeriode(value: string | null): PeriodeLaporan {
	if (value === 'hari' || value === 'minggu' || value === 'bulan' || value === 'semua') {
		return value;
	}
	return 'bulan';
}

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

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

	const periode = parsePeriode(url.searchParams.get('periode'));
	const warung = await getWarungByMemberId(locals.member.id);
	const laporan = await getLaporanData(
		locals.member.id,
		periode,
		locals.member.nama,
		warung?.nama ?? 'Warung'
	);

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