import test from "node:test";
import assert from "node:assert/strict";
import { currentApiOrigin, pairDeviceAtOrigin } from "./auth-api.js";

test("current API origin requires a browser origin instead of falling back to loopback", () => {
  assert.equal(currentApiOrigin({ origin: "https://pc.example.ts.net" }), "https://pc.example.ts.net");
  assert.throws(() => currentApiOrigin(undefined), /missing_location_origin/);
});

test("first QR scan exchanges the one-time secret directly with its PC", async () => {
  const calls = [];
  await pairDeviceAtOrigin({
    origin: "https://pc.example.ts.net",
    attemptId: "attempt-12345678",
    secret: "___________________________________________"
  }, async (...args) => {
    calls.push(args);
    return { ok: true, json: async () => ({ device: { id: "device" } }) };
  });

  assert.equal(calls.length, 1);
  assert.equal(calls[0][0], "https://pc.example.ts.net/api/auth/pair");
  assert.equal(calls[0][1].credentials, "include");
  assert.equal(calls[0][1].headers["x-code-remote-csrf"], "1");
});

test("first QR scan returns only a safe pairing error", async () => {
  await assert.rejects(
    pairDeviceAtOrigin({ origin: "https://pc.example.ts.net", attemptId: "attempt-12345678", secret: "___________________________________________" }, async () => ({
      ok: false,
      json: async () => ({ error: "private backend detail" })
    })),
    /^Error: pairing_unavailable$/
  );
});
