import { resolveAccountIdFromRequest } from "../../sync/account-identity.js";
import { getTranscriptStore } from "../../sync/transcript-store.js";
import { extractBearerToken } from "../middleware/auth.js";
function sessionKeyFromPath(pathname) {
    const prefix = "/friday-next/sessions/";
    const suffix = "/messages";
    if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix))
        return "";
    return decodeURIComponent(pathname.slice(prefix.length, -suffix.length));
}
export async function handleSessionMessagesGet(req, res) {
    if (req.method !== "GET") {
        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 accountId = resolveAccountIdFromRequest(req);
    if (!accountId) {
        res.statusCode = 403;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Unknown or missing X-Account-Id" }));
        return true;
    }
    const url = new URL(req.url ?? "/", "http://localhost");
    const sessionKey = sessionKeyFromPath(url.pathname);
    if (!sessionKey) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Missing session key in path" }));
        return true;
    }
    if (!sessionKey.includes(`friday:account:${accountId}:`) && !sessionKey.includes(`friday%3Aaccount%3A${accountId}%3A`)) {
        const legacyAllowed = sessionKey.startsWith("friday:direct:") || sessionKey.startsWith("agent:main:friday:direct:");
        if (!legacyAllowed) {
            res.statusCode = 403;
            res.setHeader("Content-Type", "application/json");
            res.end(JSON.stringify({ error: "Session does not belong to account" }));
            return true;
        }
    }
    const since = Number.parseInt(url.searchParams.get("since") ?? "0", 10);
    const limit = Number.parseInt(url.searchParams.get("limit") ?? "200", 10);
    const events = getTranscriptStore().readSince(accountId, sessionKey, Number.isFinite(since) ? since : 0, limit);
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify({ ok: true, events, nextSince: events.at(-1)?.seq ?? since }));
    return true;
}
