import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { sanitizeRedirectUrl } from '$lib/server/auth-utils';

/**
 * Auth callback handler for email verification and OAuth redirects
 * This endpoint exchanges the auth code for a session
 */
export const GET: RequestHandler = async ({ url, locals }) => {
	const code = url.searchParams.get('code');
	const next = sanitizeRedirectUrl(url.searchParams.get('next'));
	const error = url.searchParams.get('error');
	const errorDescription = url.searchParams.get('error_description');

	// Handle error from Supabase auth
	if (error) {
		console.error('Auth callback error:', error, errorDescription);
		throw redirect(303, `/login?error=${encodeURIComponent(errorDescription || error)}`);
	}

	// Exchange the code for a session
	if (code) {
		const { error: exchangeError } = await locals.supabase.auth.exchangeCodeForSession(code);

		if (exchangeError) {
			console.error('Failed to exchange code for session:', exchangeError);
			throw redirect(303, `/login?error=${encodeURIComponent('Failed to verify email. Please try again.')}`);
		}
	}

	// Redirect to the next page or dashboard
	throw redirect(303, next);
};
