import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { assertBackofficeWrite } from '$lib/server/backoffice-auth';
import { PRIVILEGE_DEFS, type PrivilegeKode } from '$lib/constants/privilege';
import {
	getAllPaket,
	updatePaketHarga,
	updatePaketInfo,
	updatePaketPrivilege
} from '$lib/server/langganan';
import type { IntervalLangganan } from '$lib/types/langganan';

export const load: PageServerLoad = async () => {
	const paketList = await getAllPaket();
	return { paketList, privilegeDefs: PRIVILEGE_DEFS };
};

export const actions: Actions = {
	updateInfo: async ({ request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const formData = await request.formData();
		const id = Number(formData.get('id'));
		const nama = String(formData.get('nama') ?? '').trim();
		const deskripsi = String(formData.get('deskripsi') ?? '').trim();
		const is_aktif = formData.has('is_aktif');

		if (!id || !nama) return fail(400, { error: 'Data paket tidak valid' });

		const ok = await updatePaketInfo(id, { nama, deskripsi, is_aktif });
		if (!ok) return fail(500, { error: 'Gagal menyimpan paket' });
		return { success: true, message: 'Info paket berhasil disimpan' };
	},

	updateHarga: async ({ request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const formData = await request.formData();
		const paketId = Number(formData.get('paket_id'));
		const interval = String(formData.get('interval') ?? '') as IntervalLangganan;
		const harga = Number(formData.get('harga'));

		if (!paketId || !['bulanan', 'tahunan'].includes(interval) || Number.isNaN(harga)) {
			return fail(400, { error: 'Data harga tidak valid' });
		}

		const ok = await updatePaketHarga(paketId, interval, harga);
		if (!ok) return fail(500, { error: 'Gagal menyimpan harga' });
		return { success: true, message: 'Harga berhasil disimpan' };
	},

	updatePrivilege: async ({ request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const formData = await request.formData();
		const paketId = Number(formData.get('paket_id'));
		const privilegeKode = String(formData.get('privilege_kode') ?? '') as PrivilegeKode;
		const tipe = String(formData.get('tipe') ?? '');

		if (!paketId || !privilegeKode) return fail(400, { error: 'Data privilege tidak valid' });

		let nilai: string;
		if (tipe === 'boolean') {
			nilai = formData.has('nilai') ? 'true' : 'false';
		} else {
			nilai = String(formData.get('nilai_number') ?? '0');
		}

		const ok = await updatePaketPrivilege(paketId, privilegeKode, nilai);
		if (!ok) return fail(500, { error: 'Gagal menyimpan privilege' });
		return { success: true, message: 'Privilege berhasil disimpan' };
	}
};
