import { extractBearerToken } from "../middleware/auth.js";
import { readJsonBody } from "../middleware/body.js";
import { processSync } from "../../sync/message-store.js";
import { toSessionStoreKey } from "../../session/session-manager.js";
function extractSessionKey(url, prefix, suffix) {
    const pathname = new URL(url, "http://localhost").pathname;
    if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix))
        return null;
    const middle = pathname.slice(prefix.length, pathname.length - suffix.length);
    return decodeURIComponent(middle) || null;
}
export async function handleSync(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;
    }
    const token = extractBearerToken(req);
    if (!token) {
        res.statusCode = 401;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Unauthorized" }));
        return true;
    }
    const rawKey = extractSessionKey(req.url ?? "/", "/friday-next/sessions/", "/sync");
    if (!rawKey) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Missing sessionKey in URL path" }));
        return true;
    }
    const sessionKey = toSessionStoreKey(rawKey);
    const body = await readJsonBody(req);
    if (!body) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Invalid JSON body" }));
        return true;
    }
    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 syncSeq = typeof body.syncSeq === "number" ? Math.floor(body.syncSeq) : 0;
    const lastServerId = typeof body.lastServerId === "string" ? body.lastServerId : undefined;
    const messages = Array.isArray(body.messages) ? body.messages : [];
    const result = processSync({ sessionKey, deviceId, syncSeq, lastServerId, messages });
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify(result));
    return true;
}
