import { NextResponse } from "next/server";
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server";

const COOKIE_NAME = "mnote_web_convex_token";
const COMPAT_HEADERS = {
  "cache-control": "no-store",
  "x-mnote-web-owner": "mnote-web",
  "x-mnote-compat-boundary": "next-auth-token-debug",
};

export const dynamic = "force-dynamic";

export async function GET() {
  const token = (await convexAuthNextjsToken())?.trim() ?? "";

  if (!token) {
    const response = NextResponse.json({ error: "未登录" }, { status: 401 });
    response.cookies.set({
      name: COOKIE_NAME,
      value: "",
      httpOnly: true,
      sameSite: "lax",
      path: "/",
      maxAge: 0,
    });
    for (const [name, value] of Object.entries(COMPAT_HEADERS)) {
      response.headers.set(name, value);
    }
    return response;
  }

  const response = NextResponse.json({
    ok: true,
    owner: "mnote-web",
    compatibility: "next-auth-token-debug",
  });
  response.cookies.set({
    name: COOKIE_NAME,
    value: token,
    httpOnly: true,
    sameSite: "lax",
    path: "/",
  });
  for (const [name, value] of Object.entries(COMPAT_HEADERS)) {
    response.headers.set(name, value);
  }
  return response;
}
