import { 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 {
	createBackofficeUser,
	findBackofficeUserByEmail,
	getAllBackofficeUsers
} from '$lib/server/backoffice-user';
import type { BackofficeRole } from '$lib/types/backoffice-user';

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

	const users = await getAllBackofficeUsers();

	return {
		users,
		roles: BACKOFFICE_ROLES,
		roleLabels: BACKOFFICE_ROLE_LABELS,
		roleDescriptions: BACKOFFICE_ROLE_DESCRIPTIONS,
		currentUserId: locals.backofficeUser.id
	};
};

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

		const formData = await request.formData();
		const nama = String(formData.get('nama') ?? '').trim();
		const email = String(formData.get('email') ?? '').trim().toLowerCase();
		const password = String(formData.get('password') ?? '');
		const role = String(formData.get('role') ?? 'admin') as BackofficeRole;

		if (!nama || nama.length < 2) {
			return fail(400, { error: 'Nama minimal 2 karakter.', field: 'nama' });
		}
		if (!email || !email.includes('@')) {
			return fail(400, { error: 'Email tidak valid.', field: 'email' });
		}
		if (!password || password.length < 6) {
			return fail(400, { error: 'Password minimal 6 karakter.', field: 'password' });
		}
		if (!BACKOFFICE_ROLES.includes(role)) {
			return fail(400, { error: 'Role tidak valid.', field: 'role' });
		}

		const existing = await findBackofficeUserByEmail(email);
		if (existing) {
			return fail(400, { error: 'Email sudah digunakan.', field: 'email' });
		}

		const id = await createBackofficeUser({ nama, email, password, role });
		if (!id) return fail(500, { error: 'Gagal membuat pengguna.' });

		throw redirect(303, `/backoffice/users/${id}?created=1`);
	}
};
