/**
 * Reactive auth state using Svelte 5 runes.
 */

import { api, setTokens, clearTokens, isAuthenticated } from './api';
import { clearAllCaches } from './stores/caches.svelte';
import type { User } from './types';

let user = $state<User | null>(null);
let loading = $state(true);

export function getAuth() {
	return {
		get user() { return user; },
		get loading() { return loading; },
		get isAdmin() { return user?.role === 'admin'; },
	};
}

export async function loadUser() {
	if (!isAuthenticated()) {
		user = null;
		loading = false;
		return;
	}
	try {
		user = await api<User>('/auth/me');
	} catch {
		user = null;
		clearTokens();
	} finally {
		loading = false;
	}
}

export async function login(username: string, password: string) {
	const data = await api<{ access_token: string; refresh_token: string }>('/auth/login', {
		method: 'POST',
		body: JSON.stringify({ username, password })
	});
	setTokens(data.access_token, data.refresh_token);
	await loadUser();
}

export async function setup(username: string, password: string) {
	const data = await api<{ access_token: string; refresh_token: string }>('/auth/setup', {
		method: 'POST',
		body: JSON.stringify({ username, password })
	});
	setTokens(data.access_token, data.refresh_token);
	await loadUser();
}

export function logout() {
	clearTokens();
	clearAllCaches();
	user = null;
	if (typeof window !== 'undefined') {
		window.location.href = '/login';
	}
}
