/**
 * GET /auth/[provider]
 *
 * Initiates the OAuth2 authorization code flow.
 * Generates a random `state` param (stored in a short-lived cookie) to
 * prevent CSRF, then redirects the browser to the provider's auth URL.
 *
 * Supported providers: google, github
 */

import { redirect, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private';
import { randomBytes } from 'node:crypto';

const PROVIDERS = {
	google: {
		authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
		scopes: 'openid email profile'
	},
	github: {
		authUrl: 'https://github.com/login/oauth/authorize',
		scopes: 'read:user user:email'
	}
} as const;

type Provider = keyof typeof PROVIDERS;

function clientId(provider: Provider): string {
	if (provider === 'google') return env.GOOGLE_CLIENT_ID ?? '';
	if (provider === 'github') return env.GITHUB_CLIENT_ID ?? '';
	return '';
}

function redirectUri(provider: Provider, origin: string): string {
	return `${origin}/auth/${provider}/callback`;
}

export const GET: RequestHandler = async ({ params, url, cookies }) => {
	const provider = params.provider as Provider;
	if (!(provider in PROVIDERS)) {
		error(404, 'Unknown OAuth provider');
	}

	const id = clientId(provider);
	if (!id) {
		error(500, `OAuth provider "${provider}" is not configured`);
	}

	// Generate state token — stored in a 10-minute cookie
	const state = randomBytes(16).toString('hex');
	cookies.set(`oauth_state_${provider}`, state, {
		path: '/',
		httpOnly: true,
		sameSite: 'lax',
		maxAge: 60 * 10 // 10 minutes
	});

	// Where to send the user after successful auth (default: home)
	const next = url.searchParams.get('next') ?? '/';
	cookies.set(`oauth_next_${provider}`, next, {
		path: '/',
		httpOnly: true,
		sameSite: 'lax',
		maxAge: 60 * 10
	});

	const origin = url.origin;
	const cfg = PROVIDERS[provider];
	const params2 = new URLSearchParams({
		client_id: id,
		redirect_uri: redirectUri(provider, origin),
		response_type: 'code',
		scope: cfg.scopes,
		state
	});

	redirect(302, `${cfg.authUrl}?${params2.toString()}`);
};
