import { writable } from 'svelte/store';
import { api, type MeResponse } from './api';

interface SessionState {
	loading: boolean;
	me: MeResponse | null;
	error: string | null;
}

export const session = writable<SessionState>({
	loading: true,
	me: null,
	error: null,
});

export async function loadSession(): Promise<void> {
	session.update((s) => ({ ...s, loading: true, error: null }));
	try {
		const me = await api.me();
		session.set({ loading: false, me, error: null });
	} catch (err) {
		const status = (err as { status?: number }).status;
		if (status === 401) {
			redirectToLogin();
			return;
		}
		session.set({
			loading: false,
			me: null,
			error: err instanceof Error ? err.message : String(err),
		});
	}
}

export function redirectToLogin(): void {
	const ret = encodeURIComponent(window.location.pathname + window.location.hash);
	window.location.href = `/auth/feishu?returnTo=${ret}`;
}

export async function logout(): Promise<void> {
	await api.logout();
	redirectToLogin();
}
