import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { loadConfig } from "./config.js";
import { createDeviceAuthStore } from "./device-auth-store.js";
import { writeSafeLog } from "./safe-logger.js";

async function readRequest() {
  let input = "";
  for await (const chunk of process.stdin) {
    input += chunk;
    if (input.length > 4096) throw new Error("pairing_request_invalid");
  }
  try {
    return JSON.parse(input);
  } catch {
    throw new Error("pairing_request_invalid");
  }
}

export async function createLocalDevicePairing(request) {
  const { config } = await loadConfig();
  const origin = typeof request?.origin === "string" ? request.origin : "";
  if (!(config.allowedOrigins ?? []).includes(origin)) throw new Error("pairing_origin_invalid");
  const pairing = await createDeviceAuthStore(config.dataDir).createPairing({ origin });
  return {
    code: pairing.code,
    expiresAt: pairing.expiresAt,
    qrPayload: pairing.qrPayload
  };
}

const invokedPath = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : "";
if (invokedPath === import.meta.url) {
  try {
    process.stdout.write(JSON.stringify(await createLocalDevicePairing(await readRequest())));
  } catch {
    writeSafeLog(console, "error", "pairing_creation_failed");
    process.exitCode = 1;
  }
}
