import { startAuthentication, startRegistration } from "@simplewebauthn/browser";
import { api, setAccessToken } from "./api";

export async function login(email, password) {
  const data = await api.post("/auth/login", { email, password });
  if (data.mfaRequired) return data;
  setAccessToken(data.accessToken);
  localStorage.setItem("br_user", JSON.stringify(data.user));
  localStorage.setItem("br_access_token", data.accessToken);
  window.__br_access_token = data.accessToken;
  localStorage.setItem("br_access_token", data.accessToken);
  window.__br_access_token = data.accessToken;
  return { user: data.user };
}

export async function completeTotp(loginToken, totpCode) {
  const data = await api.post("/auth/login/totp", { login_token: loginToken, totp_code: totpCode });
  setAccessToken(data.accessToken);
  localStorage.setItem("br_user", JSON.stringify(data.user));
  localStorage.setItem("br_access_token", data.accessToken);
  window.__br_access_token = data.accessToken;
  return data.user;
}

export async function completeWebAuthn(loginToken) {
  const options = await api.post("/auth/login/webauthn/options", { login_token: loginToken });
  const credential = await startAuthentication(options);
  const data = await api.post("/auth/login/webauthn/verify", { login_token: loginToken, credential });
  setAccessToken(data.accessToken);
  localStorage.setItem("br_user", JSON.stringify(data.user));
  localStorage.setItem("br_access_token", data.accessToken);
  window.__br_access_token = data.accessToken;
  return data.user;
}

export async function beginTotpSetup() {
  return api.post("/auth/mfa/totp/setup", {});
}

export async function finishTotpSetup(token) {
  return api.post("/auth/mfa/totp/verify", { token });
}

export async function registerPasskey() {
  const options = await api.post("/auth/mfa/webauthn/register/options", {});
  const credential = await startRegistration(options);
  return api.post("/auth/mfa/webauthn/register/verify", { credential });
}

export function logoutLocal() {
  setAccessToken("");
  localStorage.removeItem("br_user");
  localStorage.removeItem("br_access_token");
  window.__br_access_token = "";
}
