import { error, fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import {
	BACKOFFICE_ROLE_DESCRIPTIONS,
	BACKOFFICE_ROLE_LABELS,
	BACKOFFICE_ROLES
} from '$lib/constants/backoffice-role';
import { assertBackofficePermission } from '$lib/server/backoffice-auth';
import {
	deleteBackofficeUser,
	findBackofficeUserByEmail,
	getBackofficeUserById,
	updateBackofficeUser
} from '$lib/server/backoffice-user';
import type { BackofficeRole } from '$lib/types/backoffice-user';

export const load: PageServerLoad = async ({ locals, params, url }) => {
	if (!assertBackofficePermission(locals.backofficeUser, 'users')) {
		throw redirect(303, '/backoffice?error=forbidden');
	}

	const userId = Number(params.id);
	if (!userId) throw error(404, 'Pengguna tidak ditemukan');

	const user = await getBackofficeUserById(userId);
	if (!user) throw error(404, 'Pengguna tidak ditemukan');

	return {
		user,
		roles: BACKOFFICE_ROLES,
		roleLabels: BACKOFFICE_ROLE_LABELS,
		roleDescriptions: BACKOFFICE_ROLE_DESCRIPTIONS,
		currentUserId: locals.backofficeUser.id,
		created: url.searchParams.get('created') === '1'
	};
};

export const actions: Actions = {
	update: async ({ request, locals, params }) => {
		if (!assertBackofficePermission(locals.backofficeUser, 'users')) {
			return fail(403, { error: 'Tidak memiliki izin.' });
		}

		const userId = Number(params.id);
		const formData = await request.formData();
		const nama = String(formData.get('nama') ?? '').trim();
		const email = String(formData.get('email') ?? '').trim().toLowerCase();
		const role = String(formData.get('role') ?? '') as BackofficeRole;
		const is_aktif = formData.has('is_aktif');
		const password = String(formData.get('password') ?? '').trim();

		if (!userId || !nama || !email) {
			return fail(400, { error: 'Data tidak lengkap.' });
		}
		if (!BACKOFFICE_ROLES.includes(role)) {
			return fail(400, { error: 'Role tidak valid.' });
		}

		const existing = await findBackofficeUserByEmail(email);
		if (existing && existing.id !== userId) {
			return fail(400, { error: 'Email sudah digunakan pengguna lain.' });
		}

		if (userId === locals.backofficeUser.id && !is_aktif) {
			return fail(400, { error: 'Tidak bisa menonaktifkan akun sendiri.' });
		}
		if (userId === locals.backofficeUser.id && role !== locals.backofficeUser.role) {
			return fail(400, { error: 'Tidak bisa mengubah role akun sendiri.' });
		}

		const err = await updateBackofficeUser({
			id: userId,
			nama,
			email,
			role,
			is_aktif,
			password: password || undefined
		});

		if (err) return fail(400, { error: err });
		return { success: true, message: 'Pengguna berhasil disimpan.' };
	},

	delete: async ({ locals, params }) => {
		if (!assertBackofficePermission(locals.backofficeUser, 'users')) {
			return fail(403, { error: 'Tidak memiliki izin.' });
		}

		const userId = Number(params.id);
		const err = await deleteBackofficeUser(userId, locals.backofficeUser.id);
		if (err) return fail(400, { error: err });

		throw redirect(303, '/backoffice/users?deleted=1');
	}
};
