// Auth Store mit Svelte 5 Runes
import { api, type User } from '$lib/api';
import { goto } from '$app/navigation';

class AuthStore {
	user = $state<User | null>(null);
	isLoading = $state(true);
	error = $state<string | null>(null);

	get isAuthenticated() {
		return this.user !== null;
	}

	get isTeacher() {
		return this.user?.role === 'Lehrer';
	}

	async init() {
		this.isLoading = true;
		this.error = null;

		const response = await api.getMe();

		if (response.data) {
			this.user = response.data;
		} else {
			this.user = null;
		}

		this.isLoading = false;
	}

	async login(username: string, password: string): Promise<boolean> {
		this.error = null;

		const response = await api.login(username, password);

		if (response.data) {
			this.user = response.data.user;
			goto('/dashboard');
			return true;
		} else {
			this.error = response.error || 'Login fehlgeschlagen';
			return false;
		}
	}

	async register(
		email: string,
		username: string,
		password: string,
		role: 'Student' | 'Lehrer' = 'Student'
	): Promise<boolean> {
		this.error = null;

		const response = await api.register(email, username, password, role);

		if (response.data) {
			this.user = response.data.user;
			goto('/dashboard');
			return true;
		} else {
			this.error = response.error || 'Registrierung fehlgeschlagen';
			return false;
		}
	}

	async logout() {
		await api.logout();
		this.user = null;
		this.error = null;
		goto('/login');
	}

	clearError() {
		this.error = null;
	}
}

export const authStore = new AuthStore();
