import { beforeEach, describe, expect, it, vi } from "vitest";

const mockConvexAuthNextjsToken = vi.fn();

vi.mock("@convex-dev/auth/nextjs/server", () => ({
  convexAuthNextjsToken: mockConvexAuthNextjsToken,
}));

describe("/api/auth/mnote-web-token compat route", () => {
  beforeEach(() => {
    mockConvexAuthNextjsToken.mockReset();
  });

  it("有 token 时仅作为 next-auth-token-debug compat 边界写入 mnote-web cookie", async () => {
    mockConvexAuthNextjsToken.mockResolvedValue("token-demo");

    const { GET } = await import("./route");
    const response = await GET();
    const payload = await response.json();

    expect(response.status).toBe(200);
    expect(response.headers.get("x-mnote-web-owner")).toBe("mnote-web");
    expect(response.headers.get("x-mnote-compat-boundary")).toBe("next-auth-token-debug");
    expect(payload).toEqual({
      ok: true,
      owner: "mnote-web",
      compatibility: "next-auth-token-debug",
    });
    expect(response.headers.get("set-cookie")).toContain("mnote_web_convex_token=token-demo");
  });

  it("无 token 时清空兼容 cookie 并保留 mnote-web owner header", async () => {
    mockConvexAuthNextjsToken.mockResolvedValue("");

    const { GET } = await import("./route");
    const response = await GET();
    const payload = await response.json();

    expect(response.status).toBe(401);
    expect(response.headers.get("x-mnote-web-owner")).toBe("mnote-web");
    expect(response.headers.get("x-mnote-compat-boundary")).toBe("next-auth-token-debug");
    expect(payload).toEqual({ error: "未登录" });
    expect(response.headers.get("set-cookie")).toContain("mnote_web_convex_token=");
    expect(response.headers.get("set-cookie")).toContain("Max-Age=0");
  });
});
