/**
 * Authentication API functions.
 *
 * Wraps calls to POST /api/auth/login, POST /api/auth/logout, and GET /api/auth/session
 * using the central typed fetch client.
 */

import { api } from "./client";
import { ENDPOINTS } from "./endpoints";
import type { LoginResponse, LogoutResponse, SessionValidResponse } from "../types/auth";

/**
 * Authenticate with the master password.
 *
 * @param password - The master password entered by the user.
 * @returns The login response containing the session token.
 */
export async function login(password: string): Promise<LoginResponse> {
  return api.post<LoginResponse>(ENDPOINTS.authLogin, { password });
}

/**
 * Log out and invalidate the current session.
 *
 * @returns The logout confirmation message.
 */
export async function logout(): Promise<LogoutResponse> {
  return api.post<LogoutResponse>(ENDPOINTS.authLogout, {});
}

/**
 * Validate the current session with the backend.
 *
 * This is called on app mount to confirm the session is still valid on the
 * server side, rather than relying solely on the cached sessionStorage flag.
 *
 * @param signal - Optional abort signal for request cancellation.
 * @returns An object confirming the session is valid.
 * @throws {ApiError} When the session is invalid or expired (401).
 */
export async function validateSession(signal?: AbortSignal): Promise<SessionValidResponse> {
  return api.get<SessionValidResponse>(ENDPOINTS.authSession, signal);
}
