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

const COOKIE_NAME = "mnote_web_convex_token";

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,
    });
    response.headers.set("cache-control", "no-store");
    return response;
  }

  const response = NextResponse.json({ ok: true });
  response.cookies.set({
    name: COOKIE_NAME,
    value: token,
    httpOnly: true,
    sameSite: "lax",
    path: "/",
  });
  response.headers.set("cache-control", "no-store");
  return response;
}
