import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
  resetServiceTokenCache,
  verifyServiceToken,
} from "@/modules/auth/service-token";

const DEMO_TOKENS = JSON.stringify({
  "demo-host-token": {
    customerId: "CUST_001",
    permissions: ["pricing:markup:write"],
  },
});

describe("modules/auth/service-token", () => {
  beforeEach(() => {
    process.env.HOST_SERVICE_TOKENS = DEMO_TOKENS;
    resetServiceTokenCache();
  });

  afterEach(() => {
    delete process.env.HOST_SERVICE_TOKENS;
    resetServiceTokenCache();
  });

  it("正确 token + 匹配 customer_id 通过", () => {
    const result = verifyServiceToken("demo-host-token", "CUST_001");
    expect(result.customerId).toBe("CUST_001");
    expect(result.permissions).toContain("pricing:markup:write");
  });

  it("customer_id 不匹配返回 403", () => {
    expect(() => verifyServiceToken("demo-host-token", "CUST_002")).toThrow(
      expect.objectContaining({ code: "FORBIDDEN" }),
    );
  });

  it("无效 token 返回 401", () => {
    expect(() => verifyServiceToken("invalid-token", "CUST_001")).toThrow(
      expect.objectContaining({ code: "UNAUTHORIZED" }),
    );
  });
});
