import { describe, expect, it, beforeEach, afterEach } from "vitest";
import {
  EMBED_DEMO_DEFAULT_PASSWORD,
  EMBED_DEMO_ROLE,
  getEmbedDemoPassword,
  signEmbedDemoToken,
  verifyEmbedDemoToken,
} from "@/modules/embed-demo/auth";

describe("embed-demo auth", () => {
  const prevSecret = process.env.JWT_SECRET;
  const prevPassword = process.env.EMBED_DEMO_PASSWORD;

  beforeEach(() => {
    process.env.JWT_SECRET = "test-jwt-secret-for-embed-demo";
    delete process.env.EMBED_DEMO_PASSWORD;
  });

  afterEach(() => {
    if (prevSecret === undefined) {
      delete process.env.JWT_SECRET;
    } else {
      process.env.JWT_SECRET = prevSecret;
    }
    if (prevPassword === undefined) {
      delete process.env.EMBED_DEMO_PASSWORD;
    } else {
      process.env.EMBED_DEMO_PASSWORD = prevPassword;
    }
  });

  it("默认演示密码为 123456", () => {
    expect(getEmbedDemoPassword()).toBe(EMBED_DEMO_DEFAULT_PASSWORD);
  });

  it("签发与校验演示会话 JWT", async () => {
    const token = await signEmbedDemoToken("CUST_002");
    const payload = await verifyEmbedDemoToken(token);
    expect(payload.sub).toBe("CUST_002");
    expect(payload.role).toBe(EMBED_DEMO_ROLE);
  });

  it("默认登录类型为 password", async () => {
    const token = await signEmbedDemoToken("CUST_002");
    const payload = await verifyEmbedDemoToken(token);
    expect(payload.loginType).toBe("password");
  });

  it("api_key 登录类型可往返", async () => {
    const token = await signEmbedDemoToken("CUST_003", "api_key");
    const payload = await verifyEmbedDemoToken(token);
    expect(payload.sub).toBe("CUST_003");
    expect(payload.loginType).toBe("api_key");
  });
});

describe("embedDemoCookieOptions", () => {
  it("非生产默认 SameSite=lax", async () => {
    const { embedDemoCookieOptions } = await import("@/modules/embed-demo/auth");
    const prev = process.env.EMBED_COOKIE_SAMESITE;
    delete process.env.EMBED_COOKIE_SAMESITE;
    const opts = embedDemoCookieOptions();
    expect(opts.sameSite).toBe("lax");
    expect(opts.httpOnly).toBe(true);
    if (prev === undefined) delete process.env.EMBED_COOKIE_SAMESITE;
    else process.env.EMBED_COOKIE_SAMESITE = prev;
  });
});
