import { API_BASE, request } from "../../app/api.js";

export async function loadAuthenticationStatus(fetchImpl = globalThis.fetch) {
  let response;
  try {
    response = await fetchImpl(`${API_BASE}/health`, { cache: "no-store", credentials: "include" });
  } catch {
    throw new Error("pc_unreachable");
  }
  if (!response.ok) throw new Error("pc_unreachable");
  const body = await response.json();
  return body.authentication ?? { required: true, paired: false, pairingAvailable: false };
}

export const loadAuthenticationSession = () => request("/auth/session");

export const pairDevice = (input) => request("/auth/pair", { method: "POST", body: input });

export const revokeAuthenticatedDevice = (deviceId) => request(`/auth/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE" });

export async function pairDeviceAtOrigin(pairing, fetchImpl = globalThis.fetch) {
  let response;
  try {
    response = await fetchImpl(`${pairing.origin}/api/auth/pair`, {
      method: "POST",
      credentials: "include",
      headers: { "content-type": "application/json", "x-code-remote-csrf": "1" },
      body: JSON.stringify({ attemptId: pairing.attemptId, qrSecret: pairing.secret, label: "Mobile app" })
    });
  } catch {
    throw new Error("pc_unreachable");
  }
  let body;
  try { body = await response.json(); } catch { body = {}; }
  if (!response.ok) {
    const code = ["pairing_unavailable", "pairing_rate_limited"].includes(body.error) ? body.error : "pairing_unavailable";
    throw new Error(code);
  }
  return body;
}

export function currentApiOrigin(location = globalThis.location) {
  if (!location?.origin) throw new Error("missing_location_origin");
  return new URL(API_BASE, location.origin).origin;
}
