import { browser } from '$app/environment';
import { getSupabase } from '$lib/supabase';

/**
 * Redirect to Keycloak login via GoTrue OAuth proxy.
 * GoTrue handles the PKCE exchange; the browser lands at /auth/callback.
 */
export async function login(redirectTo?: string): Promise<void> {
	if (!browser) return;

	const { error } = await getSupabase().auth.signInWithOAuth({
		provider: 'keycloak',
		options: {
			redirectTo: redirectTo ?? `${window.location.origin}/auth/callback`,
			scopes: 'openid profile email'
		}
	});

	if (error) throw error;
}

/**
 * Sign out from Supabase (clears local session).
 * The Keycloak session remains active — the user won't be asked for credentials
 * again on next login unless they also log out from the Keycloak Account Console.
 */
export async function logout(): Promise<void> {
	await getSupabase().auth.signOut();
}
