import { extractBearerToken } from "../middleware/auth.js";
import { getMessagesBefore } from "../../sync/message-store.js";
import { toSessionStoreKey } from "../../session/session-manager.js";
export async function handleMessagesList(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;
    }
    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 = "/messages";
    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 before = url.searchParams.get("before") ?? undefined;
    const limitRaw = url.searchParams.get("limit");
    const limit = limitRaw ? parseInt(limitRaw, 10) : 25;
    if (limitRaw && (isNaN(limit) || limit < 1 || limit > 50)) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Invalid limit (1-50)" }));
        return true;
    }
    const result = getMessagesBefore(sessionKey, before, limit);
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify(result));
    return true;
}
