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

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

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

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

export const actions: Actions = {
	hapus: async ({ request, locals }) => {
		const id = Number((await request.formData()).get('id'));
		if (!id) return fail(400, { error: 'Transaksi tidak valid.' });

		const deleted = await deleteCatatan(locals.member!.id, id);
		if (!deleted) return fail(404, { error: 'Transaksi tidak ditemukan.' });

		return { deleted: true };
	}
};
