// Auth endpoints (docs/11-BACKEND-PHASE1.md §2.0). ERPCore proxies the AuthHex IdP and
// delivers the session as httpOnly cookies — there is no token for JS to hold or attach.
import { apiRequest } from "@/lib/api-client"
import { AuthSession, LoginRequest, RegisterRequest } from "@/types/auth"
import { MeResponse } from "@/types/rbac"

export const authApi = {
  /** Authoritative role + permitted sidebar nav codes for the current session. */
  me(): Promise<MeResponse> {
    return apiRequest<MeResponse>("/auth/me")
  },

  /** Sets erp_at / erp_rt / XSRF-TOKEN cookies on success. Body carries no tokens. */
  login(request: LoginRequest): Promise<AuthSession> {
    return apiRequest<AuthSession>("/auth/login", { method: "POST", body: request })
  },

  /** Also issues a session, same as login. */
  register(request: RegisterRequest): Promise<AuthSession> {
    return apiRequest<AuthSession>("/auth/register", { method: "POST", body: request })
  },

  /**
   * Clears all three cookies server-side.
   *
   * `userId` is optional and normally null: AuthHex omits it from its own login response,
   * so the browser never learns it. The server falls back to the session token's UserId
   * claim, and clears the cookies regardless of what the upstream revoke does.
   */
  logout(userId: string | null = null): Promise<void> {
    return apiRequest<void>("/auth/logout", { method: "POST", body: { userId } })
  },

  /** Exchanges the path-scoped erp_rt cookie for a fresh session. */
  refresh(): Promise<AuthSession> {
    return apiRequest<AuthSession>("/auth/refresh-token", { method: "POST", body: {} })
  },
}
