/** Shared auth helpers for token management. */

const TOKEN_KEY = 'auth_token';

/** Returns the stored JWT token, or null if not authenticated. */
export function getAuthToken(): string | null {
	if (typeof localStorage !== 'undefined') {
		return localStorage.getItem(TOKEN_KEY);
	}
	return null;
}

/** Returns true if the user has a stored auth token. */
export function isAuthenticated(): boolean {
	return getAuthToken() !== null;
}

/** Stores the JWT token after successful login. */
export function setAuthToken(token: string): void {
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem(TOKEN_KEY, token);
	}
}

/** Removes the stored token and redirects to login. */
export function clearAuth(): void {
	if (typeof localStorage !== 'undefined') {
		localStorage.removeItem(TOKEN_KEY);
	}
}

/** Exchanges the httpOnly OIDC cookie for a JWT token via the server endpoint. */
export async function exchangeOidcToken(): Promise<string | null> {
	try {
		const res = await fetch('/api/auth/oidc/token', { method: 'POST' });
		if (!res.ok) return null;
		const envelope = await res.json();
		if (envelope.success && envelope.data?.token) {
			return envelope.data.token;
		}
		return null;
	} catch {
		return null;
	}
}
