import { getOrCreateAccountId } from "../../sync/account-identity.js";
import { getInstallationId } from "../../sync/installation-id.js";
import { extractBearerToken } from "../middleware/auth.js";
import { readJsonBody } from "../middleware/body.js";
export async function handlePair(req, res) {
    if (req.method !== "POST") {
        res.statusCode = 405;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Method Not Allowed" }));
        return true;
    }
    if (!extractBearerToken(req)) {
        res.statusCode = 401;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Unauthorized: bearer token mismatch" }));
        return true;
    }
    const body = await readJsonBody(req);
    const deviceId = typeof body?.deviceId === "string" ? body.deviceId.trim() : "";
    if (!deviceId) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Missing required field: deviceId" }));
        return true;
    }
    const claimAccountId = typeof body?.claimAccountId === "string" ? body.claimAccountId.trim() : undefined;
    const claim = body?.claim && typeof body.claim === "object" && !Array.isArray(body.claim)
        ? body.claim
        : {};
    const result = getOrCreateAccountId({
        deviceId,
        claimAccountId,
        claimConfirmed: claim.confirmed === true,
    });
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify({ ok: true, installationId: getInstallationId(), ...result }));
    return true;
}
