import { draftMode } from "next/headers";
import * as API from "./api";
import { getConfig } from "./config";
import { NextResponse } from "next/server";
function normalizeToken(value) {
    if (!value)
        return undefined;
    const normalized = value.replace(/^Bearer\s+/i, "").trim();
    return normalized || undefined;
}
async function readBody(request) {
    const contentType = request.headers.get("content-type") || "";
    if (!contentType.includes("application/json")) {
        return {};
    }
    try {
        return (await request.json());
    }
    catch {
        return {};
    }
}
export default async function draft(request) {
    try {
        const { edenApi } = getConfig();
        const url = new URL(request.url);
        const searchParams = url.searchParams;
        const body = await readBody(request);
        const token = normalizeToken(request.headers.get("authorization") ||
            searchParams.get("token") ||
            (typeof body.token === "string" ? body.token : undefined));
        const status = typeof body.status === "boolean"
            ? String(body.status)
            : typeof body.status === "string"
                ? body.status
                : searchParams.get("status");
        if (!token) {
            return NextResponse.json({ error: "no token provided" }, { status: 403 });
        }
        const { message } = await API.checkToken(edenApi, token);
        if (message !== "token-valid") {
            return NextResponse.json({ error: "invalid token" }, { status: 403 });
        }
        const draft = await draftMode();
        const enable = status === "true";
        if (enable) {
            draft.enable();
        }
        else {
            draft.disable();
        }
        return NextResponse.json({ message: enable ? "Draft mode enabled" : "Draft mode disabled" }, { status: 200 });
    }
    catch (err) {
        return NextResponse.json({ error: "server error" }, { status: 500 });
    }
}
