const BASE_URL = import.meta.env.VITE_API_URL;

const makeRequest = async (
  url: string,
  body: object,
  error = "Une erreur est survenue",
  method = "POST"
) => {
  const response = await fetch(BASE_URL + url, {
    method,
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });

  const data = await response.json();
  if (!response.ok) throw new Error(data.error || error);
  return data?.data || data;
};

export const requestLogin = async (email: string, token: string) => {
  return makeRequest(
    "/auth/request",
    { email, token },
    "Échec de la demande de connexion"
  );
};

export const verifyOtp = async ({
  otpCode,
  email,
}: {
  otpCode: string;
  email: string;
}) => {
  return makeRequest(
    "/auth/verify",
    { email, code: otpCode },
    "Code de vérification invalide"
  );
};

export const sendOtp = async (email: string) => {
  return makeRequest(
    "/auth/send-otp",
    { email },
    "Échec de l'envoi du code de vérification"
  );
};
