import { describe, expect, it } from "vitest";
import { forbidden } from "@/modules/auth/errors";
import { resolveEnvServiceToken } from "@/modules/auth/service-token-env";

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

describe("middleware host auth gate", () => {
  it("env token 带 X-Customer-Id 时命中快路径", () => {
    process.env.HOST_SERVICE_TOKENS = DEMO_TOKENS;
    const verified = resolveEnvServiceToken("demo-host-token", "CUST_001");
    expect(verified?.customerId).toBe("CUST_001");
  });

  it("DB token 带 X-Customer-Id 时不应抛错，应返回 null 交给路由层 DB 校验", () => {
    process.env.HOST_SERVICE_TOKENS = DEMO_TOKENS;
    const verified = resolveEnvServiceToken(
      "chj_QUNFn-Le9biXM4UTFv5L4z9qouAKmBu7",
      "CUST_002",
    );
    expect(verified).toBeNull();
  });

  it("env token 与客户 ID 不匹配时仍抛 forbidden", () => {
    process.env.HOST_SERVICE_TOKENS = DEMO_TOKENS;
    expect(() =>
      resolveEnvServiceToken("demo-host-token", "CUST_002"),
    ).toThrow(forbidden("customer_id 与令牌租户不匹配"));
  });
});
