import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	buildGoogleAuthUrl,
	getOAuthStateCookieOptions,
	isGoogleAuthEnabled,
	OAUTH_STATE_COOKIE
} from '$lib/server/google-auth';

export const GET: RequestHandler = async ({ url, cookies }) => {
	if (!isGoogleAuthEnabled()) {
		throw redirect(303, '/login');
	}

	const mode = url.searchParams.get('mode') === 'register' ? 'register' : 'login';
	const { url: authUrl, state } = buildGoogleAuthUrl(url.origin, mode);

	cookies.set(OAUTH_STATE_COOKIE, state, getOAuthStateCookieOptions());

	throw redirect(302, authUrl);
};
