import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import type { FilterHutangPiutang } from '$lib/types/hutang-piutang';
import {
	deleteHutangPiutang,
	getHutangPiutangList,
	lunasiHutangPiutang
} from '$lib/server/hutang-piutang';

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

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

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

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

		const ok = await lunasiHutangPiutang(locals.member!.id, id);
		if (!ok) return fail(404, { error: 'Data tidak ditemukan.' });

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

		const ok = await deleteHutangPiutang(locals.member!.id, id);
		if (!ok) return fail(404, { error: 'Data tidak ditemukan.' });

		return { deleted: true };
	}
};
