import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { redirect, type RequestEvent } from '@sveltejs/kit';
import { CURRENT_DID_KEY, CURRENT_HANDLE_KEY } from './accounts';
import type { Auth } from '../auth.svelte';

export interface RequireAuthResult {
	did: string;
	handle: string;
}

const loginWithReturn = (returnUrl: string): string =>
	`/login?return_url=${encodeURIComponent(returnUrl)}`;

export const requireAuth = (event: RequestEvent): RequireAuthResult => {
	const did = event.cookies.get(CURRENT_DID_KEY);
	if (!did) {
		redirect(302, loginWithReturn(event.url.pathname + event.url.search));
	}
	return { did, handle: event.cookies.get(CURRENT_HANDLE_KEY) ?? did };
};

export const requireAuthClient = (auth: Auth, url: URL): boolean => {
	if (auth.currentDid) return true;
	void goto(resolve(loginWithReturn(url.pathname + url.search) as '/login'), {
		replaceState: true
	});
	return false;
};
