import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import type { FilterPeriode } from '$lib/types/transaksi';
import { deletePenjualan, getPenjualanList } from '$lib/server/transaksi';

function parseFilter(value: string | null): FilterPeriode {
	if (value === 'minggu' || value === 'semua') return value;
	return 'hari';
}

export const load: PageServerLoad = async ({ locals, url }) => {
	const filter = parseFilter(url.searchParams.get('filter'));
	const success = url.searchParams.get('success') === '1';

	const data = await getPenjualanList(locals.member!.id, filter);

	return {
		...data,
		success
	};
};

export const actions: Actions = {
	hapus: async ({ request, locals }) => {
		const formData = await request.formData();
		const id = Number(formData.get('id'));

		if (!id || Number.isNaN(id)) {
			return fail(400, { error: 'Transaksi tidak valid.' });
		}

		const deleted = await deletePenjualan(locals.member!.id, id);

		if (!deleted) {
			return fail(404, { error: 'Transaksi tidak ditemukan.' });
		}

		return { deleted: true };
	}
};
