import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import {
	createSessionToken,
	getSessionCookieOptions,
	SESSION_COOKIE
} from '$lib/server/auth';
import { isGoogleAuthEnabled } from '$lib/server/google-auth';
import { registerWithEmail } from '$lib/server/register';

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

	const oauthError = url.searchParams.get('error');

	return {
		googleEnabled: isGoogleAuthEnabled(),
		oauthError: oauthError ? decodeURIComponent(oauthError) : null
	};
};

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

		if (password !== konfirmasi) {
			return fail(400, {
				error: 'Konfirmasi password tidak cocok.',
				field: 'konfirmasi',
				nama,
				email
			});
		}

		const result = await registerWithEmail({ nama, email, password });

		if (!result.ok) {
			return fail(400, {
				error: result.error,
				field: result.field,
				nama,
				email
			});
		}

		const token = createSessionToken(result.member);
		cookies.set(SESSION_COOKIE, token, getSessionCookieOptions());

		throw redirect(303, '/dashboard');
	}
};
