import { error, 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 {
	assignMemberLangganan,
	getAdminMemberDetail,
	hasPrivilege,
	getPrivilegeNumber,
	updateMemberPrivilegeOverrides
} from '$lib/server/langganan';
import type { IntervalLangganan } from '$lib/types/langganan';

export const load: PageServerLoad = async ({ params, parent }) => {
	const { canWrite } = await parent();
	const memberId = Number(params.id);
	if (!memberId) throw error(404, 'Member tidak ditemukan');

	const detail = await getAdminMemberDetail(memberId);
	if (!detail) throw error(404, 'Member tidak ditemukan');

	const privilegeSummary = PRIVILEGE_DEFS.map((def) => ({
		...def,
		aktif: def.tipe === 'boolean' ? hasPrivilege(detail.entitlements, def.kode) : null,
		nilai:
			def.tipe === 'number'
				? getPrivilegeNumber(detail.entitlements, def.kode) === 0
					? '∞'
					: String(getPrivilegeNumber(detail.entitlements, def.kode))
				: null
	}));

	return { ...detail, privilegeDefs: PRIVILEGE_DEFS, privilegeSummary, canWrite };
};

export const actions: Actions = {
	assignPaket: async ({ params, request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const memberId = Number(params.id);
		const formData = await request.formData();
		const paketId = Number(formData.get('paket_id'));
		const interval = String(formData.get('interval') ?? 'bulanan') as IntervalLangganan;
		const berakhirAt = String(formData.get('berakhir_at') ?? '').trim() || undefined;
		const keterangan = String(formData.get('keterangan') ?? '').trim();

		if (!memberId || !paketId) return fail(400, { error: 'Paket tidak valid' });

		const ok = await assignMemberLangganan({
			memberId,
			paketId,
			interval,
			berakhirAt,
			keterangan
		});

		if (!ok) return fail(500, { error: 'Gagal assign paket' });
		return { success: true, message: 'Paket berhasil diassign ke member' };
	},

	updateOverrides: async ({ params, request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const memberId = Number(params.id);
		const formData = await request.formData();

		const overrides = PRIVILEGE_DEFS.map((def) => {
			let nilai = '';
			if (def.tipe === 'boolean') {
				if (formData.has(`override_${def.kode}`)) {
					nilai = formData.get(`override_${def.kode}`) === '1' ? 'true' : 'false';
				}
			} else {
				const raw = String(formData.get(`override_${def.kode}`) ?? '').trim();
				if (raw) nilai = raw;
			}
			return {
				kode: def.kode as PrivilegeKode,
				nilai,
				keterangan: String(formData.get(`ket_${def.kode}`) ?? '').trim()
			};
		}).filter((o) => o.nilai);

		const ok = await updateMemberPrivilegeOverrides(memberId, overrides);
		if (!ok) return fail(500, { error: 'Gagal menyimpan override' });
		return { success: true, message: 'Override privilege berhasil disimpan' };
	},

};
