import { getApiBaseUrl } from '$lib/api';
import { authenticatedFetch } from '$lib/auth';

/**
 * Types pour les sessions utilisateur.
 *
 * @see Story 1.6 - Gestion des sessions
 */
export interface Session {
	family_id: string;
	device: string;
	browser: string;
	os: string;
	location: string;
	created_at: string;
	last_activity_at: string;
	is_current: boolean;
}

export interface SessionsResponse {
	sessions: Session[];
}

export interface RevokeAllResponse {
	message: string;
	revoked_count: number;
}

/**
 * Récupère toutes les sessions actives de l'utilisateur.
 */
export async function getSessions(): Promise<Session[]> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/sessions`);

	if (!response.ok) {
		throw new Error('Failed to fetch sessions');
	}

	const data: SessionsResponse = await response.json();
	return data.sessions;
}

/**
 * Révoque une session spécifique.
 */
export async function revokeSession(familyId: string): Promise<void> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/sessions/${familyId}`, {
		method: 'DELETE'
	});

	if (!response.ok) {
		if (response.status === 403) {
			throw new Error('Cannot revoke current session');
		}
		throw new Error('Failed to revoke session');
	}
}

/**
 * Révoque toutes les sessions sauf la session courante.
 */
export async function revokeAllSessions(): Promise<number> {
	const apiUrl = getApiBaseUrl();
	const response = await authenticatedFetch(`${apiUrl}/me/sessions`, {
		method: 'DELETE'
	});

	if (!response.ok) {
		throw new Error('Failed to revoke all sessions');
	}

	const data: RevokeAllResponse = await response.json();
	return data.revoked_count;
}
