import { extractBearerToken } from "../middleware/auth.js";
import { readJsonBody } from "../middleware/body.js";
import { importMessages, ConflictError } from "../../sync/message-store.js";
import { toSessionStoreKey } from "../../session/session-manager.js";
export async function handleImport(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 url = new URL(req.url ?? "/", "http://localhost");
    const pathname = url.pathname;
    const prefix = "/friday-next/sessions/";
    const suffix = "/import";
    if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix)) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Missing sessionKey in URL path" }));
        return true;
    }
    const rawKey = pathname.slice(prefix.length, pathname.length - suffix.length);
    const sessionKey = toSessionStoreKey(decodeURIComponent(rawKey));
    const body = await readJsonBody(req, 50 * 1024 * 1024); // 50 MB for bulk import
    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 messages = Array.isArray(body.messages) ? body.messages : [];
    if (messages.length === 0) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Missing required field: messages (non-empty array)" }));
        return true;
    }
    try {
        const result = importMessages({ sessionKey, deviceId, messages });
        res.statusCode = 200;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify(result));
    }
    catch (err) {
        if (err instanceof ConflictError) {
            res.statusCode = 409;
            res.setHeader("Content-Type", "application/json");
            res.end(JSON.stringify({ error: err.message }));
        }
        else {
            throw err;
        }
    }
    return true;
}
