import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	createSessionToken,
	getSessionCookieOptions,
	SESSION_COOKIE
} from '$lib/server/auth';
import {
	exchangeGoogleCode,
	getOAuthStateCookieOptions,
	OAUTH_STATE_COOKIE,
	verifyOAuthState
} from '$lib/server/google-auth';
import { authenticateWithGoogle } from '$lib/server/register';

export const GET: RequestHandler = async ({ url, cookies }) => {
	const code = url.searchParams.get('code');
	const state = url.searchParams.get('state');
	const storedState = cookies.get(OAUTH_STATE_COOKIE);
	const oauthError = url.searchParams.get('error');

	cookies.delete(OAUTH_STATE_COOKIE, getOAuthStateCookieOptions());

	if (oauthError || !code || !state || !storedState || state !== storedState) {
		throw redirect(303, '/login?error=oauth');
	}

	if (!verifyOAuthState(state)) {
		throw redirect(303, '/login?error=oauth');
	}

	try {
		const googleUser = await exchangeGoogleCode(code, url.origin);
		const result = await authenticateWithGoogle(googleUser);

		if (!result.ok) {
			throw redirect(303, `/daftar?error=${encodeURIComponent(result.error)}`);
		}

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

		throw redirect(303, '/dashboard');
	} catch (err) {
		if (err && typeof err === 'object' && 'status' in err && err.status === 303) {
			throw err;
		}
		throw redirect(303, '/login?error=google');
	}
};
