import { fail, redirect } from '@sveltejs/kit';
import bcrypt from 'bcryptjs';
import type { Actions, PageServerLoad } from './$types';
import {
	BACKOFFICE_SESSION_COOKIE,
	createBackofficeSessionToken,
	getBackofficeSessionCookieOptions
} from '$lib/server/auth';
import { findBackofficeUserByEmail } from '$lib/server/backoffice-user';

export const load: PageServerLoad = async ({ locals, url }) => {
	if (locals.backofficeUser) {
		throw redirect(303, '/backoffice');
	}

	return {
		forbidden: url.searchParams.get('error') === 'forbidden'
	};
};

export const actions: Actions = {
	default: async ({ request, cookies }) => {
		const formData = await request.formData();
		const email = String(formData.get('email') ?? '').trim().toLowerCase();
		const password = String(formData.get('password') ?? '');

		if (!email || !password) {
			return fail(400, { error: 'Email dan password wajib diisi.', email });
		}

		const user = await findBackofficeUserByEmail(email);

		if (!user || !user.is_aktif) {
			return fail(401, {
				error: 'Email atau password salah.',
				email
			});
		}

		const valid = await bcrypt.compare(password, user.password);
		if (!valid) {
			return fail(401, { error: 'Email atau password salah.', email });
		}

		const token = createBackofficeSessionToken({
			id: user.id,
			nama: user.nama,
			email: user.email,
			role: user.role
		});

		cookies.set(BACKOFFICE_SESSION_COOKIE, token, getBackofficeSessionCookieOptions());
		throw redirect(303, '/backoffice');
	}
};
