import { api } from "./http";
import type {
  AuthTokens,
  AuthUser,
  ForgotPasswordRequestPayload,
  ForgotPasswordVerifyPayload,
  LoginResponse,
  ResetTicket,
  SetPasswordPayload,
} from "./types";

export const loginRequest = async (payload: {
  email: string;
  password: string;
}) => {
  const response = await api.post<LoginResponse>("/auth/login", payload);
  return response.data;
};

export const verifyMfaRequest = async (payload: {
  email: string;
  otp: string;
}) => {
  const response = await api.post<AuthTokens>("/auth/mfa-verify", payload);
  return response.data;
};

export const getMeRequest = async () => {
  const response = await api.get<AuthUser>("/me");
  return response.data;
};

// The three calls below drive the unauthenticated forgot-password flow.
// Responses under /api/auth are *flattened* by the API's response
// interceptor ({ success, ...payload }), so there is no `.data.data` here.

export const requestPasswordResetRequest = async (
  payload: ForgotPasswordRequestPayload,
) => {
  await api.post("/auth/forgot-password/request", payload);
};

export const verifyPasswordResetOtpRequest = async (
  payload: ForgotPasswordVerifyPayload,
) => {
  const response = await api.post<ResetTicket>(
    "/auth/forgot-password/verify",
    payload,
  );
  return response.data;
};

/**
 * Spend the reset ticket minted by {@link verifyPasswordResetOtpRequest}.
 * Carries its own userId/verificationCode and never touches the session.
 */
export const resetPasswordRequest = async (payload: SetPasswordPayload) => {
  await api.patch("/auth/set-password", payload);
};
