import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { createStokOpname, getOpnameFormBarang } from '$lib/server/opname';
import { getTodayDateString, isValidDateString } from '$lib/utils/parse';

export const load: PageServerLoad = async ({ locals }) => {
	const barangList = await getOpnameFormBarang(locals.member!.id);
	return {
		barangList,
		tanggalDefault: getTodayDateString()
	};
};

export const actions: Actions = {
	default: async ({ request, locals }) => {
		const formData = await request.formData();
		const tanggal = String(formData.get('tanggal') ?? '').trim();
		const keterangan = String(formData.get('keterangan') ?? '').trim();

		if (!isValidDateString(tanggal)) {
			return fail(400, { error: 'Tanggal tidak valid.' });
		}

		const items: { barangId: number; stokFisik: number }[] = [];

		for (const [key, value] of formData.entries()) {
			if (key.startsWith('stok_fisik_')) {
				const barangId = Number(key.replace('stok_fisik_', ''));
				const stokFisik = Number(value);
				if (barangId && !Number.isNaN(stokFisik)) {
					items.push({ barangId, stokFisik });
				}
			}
		}

		if (items.length === 0) {
			return fail(400, { error: 'Tidak ada data barang untuk opname.' });
		}

		try {
			await createStokOpname({
				memberId: locals.member!.id,
				tanggal,
				keterangan,
				items
			});
		} catch (error) {
			if (error instanceof Error && error.message === 'NO_ITEMS') {
				return fail(400, { error: 'Data opname tidak valid.' });
			}
			return fail(500, { error: 'Gagal menyimpan opname. Pastikan MySQL berjalan.' });
		}

		throw redirect(303, '/stok/opname?success=1');
	}
};
