import { parseDevicePairingPayload } from "../../../../../packages/shared/src/device-pairing.js";

async function scanQrValue(scanner, labels = {}) {
  const activeScanner = scanner ?? (await import("@capacitor/barcode-scanner")).CapacitorBarcodeScanner;
  const result = await activeScanner.scanBarcode({
    hint: 0,
    scanInstructions: labels.instructions ?? " ",
    scanButton: false,
    cancelButtonAccessibilityLabel: labels.cancel ?? "Cancel"
  });
  const address = String(result?.ScanResult ?? "").trim();
  if (!address) throw new Error("invalid_qr_code");
  return address;
}

export const scanPcConnectionQr = scanQrValue;

export async function scanDevicePairingQr(scanner, labels = {}) {
  return parseDevicePairingPayload(await scanQrValue(scanner, labels));
}

export async function scanConnectionSetupQr(scanner, labels = {}) {
  const value = await scanQrValue(scanner, labels);
  if (!value.startsWith("crm-pair:")) return { origin: value, pairing: null };
  const pairing = parseDevicePairingPayload(value);
  return { origin: pairing.origin, pairing };
}
