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

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

	const errorCode = url.searchParams.get('error');
	let oauthError: string | null = null;
	if (errorCode === 'oauth') {
		oauthError = 'Login Google dibatalkan atau sesi kedaluwarsa. Silakan coba lagi.';
	} else if (errorCode === 'google') {
		oauthError = 'Gagal masuk dengan Google. Periksa konfigurasi atau coba lagi.';
	}

	return {
		googleEnabled: isGoogleAuthEnabled(),
		oauthError
	};
};

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 member = await findMemberByEmail(email);

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

		if (!member.password || isGoogleOnlyMember(member)) {
			return fail(401, {
				error: 'Akun ini terdaftar via Google. Silakan masuk dengan Google.',
				email
			});
		}

		const valid = await bcrypt.compare(password, member.password);

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

		const token = createSessionToken({
			id: member.id,
			nama: member.nama,
			email: member.email
		});

		cookies.set(SESSION_COOKIE, token, getSessionCookieOptions());

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