import { redirect } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

/**
 * Auth verify handler for email links from Supabase/GoTrue
 * This handles invite, recovery, confirmation, and email change tokens
 *
 * Flow:
 * 1. User clicks link in email (e.g., password reset)
 * 2. Link goes to /auth/verify?token=...&type=recovery&redirect_to=...
 * 3. This handler extracts parameters and redirects to the appropriate SvelteKit page
 */
export const GET: RequestHandler = async ({ url, locals }) => {
	const token = url.searchParams.get('token');
	const type = url.searchParams.get('type');
	const redirectTo = url.searchParams.get('redirect_to');

	console.log('Auth verify handler:', { token: token?.substring(0, 20) + '...', type, redirectTo });

	// Handle different verification types
	if (type === 'recovery' || type === 'rec') {
		// Password reset - redirect to reset password page with token
		const resetUrl = new URL('/auth/reset-password', url.origin);
		if (token) resetUrl.searchParams.set('token', token);
		if (type) resetUrl.searchParams.set('type', type);
		throw redirect(303, resetUrl.toString());
	}

	if (type === 'invite' || type === 'inv') {
		// Member invitation - redirect to set password page
		const resetUrl = new URL('/auth/reset-password', url.origin);
		if (token) resetUrl.searchParams.set('token', token);
		resetUrl.searchParams.set('type', 'invite');
		throw redirect(303, resetUrl.toString());
	}

	if (type === 'signup' || type === 'confirmation' || type === 'email_change') {
		// Email confirmation - try to verify directly then redirect
		if (token) {
			try {
				const { error } = await locals.supabase.auth.verifyOtp({
					token_hash: token,
					type: type === 'email_change' ? 'email_change' : 'signup'
				});

				if (error) {
					console.error('Email verification error:', error);
					throw redirect(303, `/login?error=${encodeURIComponent(error.message)}`);
				}

				// Success - redirect to dashboard
				throw redirect(303, redirectTo || '/dashboard');
			} catch (e) {
				if (e && typeof e === 'object' && 'status' in e) {
					// This is a redirect, rethrow it
					throw e;
				}
				console.error('Verification error:', e);
				throw redirect(303, `/login?error=${encodeURIComponent('Verification failed. Please try again.')}`);
			}
		}
	}

	// Default: redirect to login with error
	throw redirect(303, `/login?error=${encodeURIComponent('Invalid verification link')}`);
};
