import { get, post, proj } from "./http";
import type { Access, LoginResult, Me } from "./types";
import type { Session } from "./types-extra";

/** Identity endpoints (master plan G.1). Session is an httpOnly cookie set by the server. */
export const login = (email: string, password: string, remember = false) =>
  post<LoginResult>("/auth/login", { email: email.trim().toLowerCase(), password, remember });
export const verifyTwoFactor = (challengeId: string, code: string) =>
  post<LoginResult>("/auth/2fa/verify", { challengeId, code });
export const resendTwoFactor = (challengeId: string) =>
  post<{ ok: true }>("/auth/2fa/resend", { challengeId });
export const logout = () => post<void>("/auth/logout");
export const getMe = () => get<Me>("/auth/me");
export const getAccess = () => get<Access>(proj("/access/me"));
export const forgotPassword = (email: string) =>
  post<{ ok: true }>("/auth/password/forgot", { email });
export const resetPassword = (token: string, password: string) =>
  post<{ ok: true }>("/auth/password/reset", { token, new: password });
export const changePassword = (current: string, password: string) =>
  post<{ ok: true }>("/auth/password/change", { current, new: password });
export const getInvite = (token: string) =>
  get<{
    name: string;
    email: string;
    roleLabel: string;
    providerName?: string;
    requires2fa: boolean;
  }>("/auth/invites", { token });
export const acceptInvite = (token: string, name: string, password: string) =>
  post<{ ok: true }>("/auth/invites/accept", { token, name, password });
export const listSessions = () => get<Session[]>("/auth/sessions");
export const revokeSession = (id: string) => post<void>(`/auth/sessions/${id}/revoke`);
export const setupTotp = () => post<{ secret: string; otpauthUrl: string }>("/auth/2fa/totp/setup");
export const confirmTotp = (code: string) => post<{ ok: true }>("/auth/2fa/totp/confirm", { code });
/** Test server only: empty in production. */
export const listDemoAccounts = () =>
  get<{ id: string; name: string; role: string; provider: string | null; scope: string | null }[]>(
    "/auth/demo",
  );
export const demoLogin = (id: string) => post<LoginResult>(`/auth/demo/${id}`);
