import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { assertBackofficeWrite } from '$lib/server/backoffice-auth';
import { LANDING_KONTEN_GROUPS, LANDING_ITEM_TYPES } from '$lib/constants/landing-defaults';
import {
	deleteLandingItem,
	getLandingItems,
	getLandingKontenMap,
	saveLandingItem,
	toggleLandingItem,
	updateLandingKontenBulk
} from '$lib/server/landing';
import type { LandingItemTipe } from '$lib/types/landing';

const VALID_TIPES: LandingItemTipe[] = ['feature', 'step', 'faq', 'stat', 'mobile_highlight'];

export const load: PageServerLoad = async () => {
	const [konten, items] = await Promise.all([getLandingKontenMap(), getLandingItems(false)]);

	return {
		konten,
		items,
		kontenGroups: LANDING_KONTEN_GROUPS,
		itemTypes: LANDING_ITEM_TYPES
	};
};

export const actions: Actions = {
	saveKonten: async ({ request, locals }) => {
		if (!assertBackofficeWrite(locals.backofficeUser)) {
			return fail(403, { error: 'Tidak memiliki izin mengubah data.' });
		}
		const formData = await request.formData();
		const groupId = String(formData.get('group_id') ?? '');
		const group = LANDING_KONTEN_GROUPS.find((g) => g.id === groupId);

		if (!group) return fail(400, { error: 'Grup konten tidak valid' });

		const updates: Record<string, string> = {};
		for (const field of group.fields) {
			updates[field.key] = String(formData.get(field.key) ?? '');
		}

		await updateLandingKontenBulk(updates);
		return { success: true, message: `${group.label} berhasil disimpan` };
	},

	saveItem: 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') || 0);
		const tipe = String(formData.get('tipe') ?? '') as LandingItemTipe;
		const urutan = Number(formData.get('urutan') ?? 0);
		const judul = String(formData.get('judul') ?? '').trim();
		const deskripsi = String(formData.get('deskripsi') ?? '').trim();
		const icon = String(formData.get('icon') ?? '').trim();
		const warna = String(formData.get('warna') ?? '').trim();
		const is_aktif = formData.has('is_aktif');

		if (!VALID_TIPES.includes(tipe) || !judul) {
			return fail(400, { error: 'Data item tidak valid' });
		}

		const savedId = await saveLandingItem({
			id: id || undefined,
			tipe,
			urutan: Number.isNaN(urutan) ? 0 : urutan,
			judul,
			deskripsi: deskripsi || null,
			icon: icon || null,
			warna: warna || null,
			is_aktif
		});

		if (!savedId) return fail(500, { error: 'Gagal menyimpan item' });
		return { success: true, message: id ? 'Item berhasil diperbarui' : 'Item berhasil ditambahkan' };
	},

	deleteItem: 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'));

		if (!id) return fail(400, { error: 'Item tidak valid' });

		const ok = await deleteLandingItem(id);
		if (!ok) return fail(500, { error: 'Gagal menghapus item' });
		return { success: true, message: 'Item berhasil dihapus' };
	},

	toggleItem: 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 is_aktif = formData.get('is_aktif') === '1';

		if (!id) return fail(400, { error: 'Item tidak valid' });

		const ok = await toggleLandingItem(id, is_aktif);
		if (!ok) return fail(500, { error: 'Gagal mengubah status item' });
		return { success: true, message: is_aktif ? 'Item diaktifkan' : 'Item dinonaktifkan' };
	}
};
