import { afterEach, describe, expect, it } from "vitest";
import {
  decryptSecret,
  encryptSecret,
} from "@/modules/customer/token-crypto";
import {
  getFlockLoginSource,
  hasEffectiveFlockLogin,
  runWithFlockLoginContext,
} from "@/lib/flock/login-context";
import { serializeProviderCredentialAdminView } from "@/modules/customer/provider-credentials";

describe("encryptSecret / decryptSecret", () => {
  it("往返一致", () => {
    const plain = "daetrDG#%%^Ydad12";
    expect(decryptSecret(encryptSecret(plain))).toBe(plain);
  });

  it("空/非法密文返回 null", () => {
    expect(decryptSecret(null)).toBeNull();
    expect(decryptSecret("")).toBeNull();
    expect(decryptSecret("@@@")).toBeNull();
  });
});

describe("serializeProviderCredentialAdminView", () => {
  it("回传完整邮箱与明文密码", () => {
    const password = "Secret#1";
    const view = serializeProviderCredentialAdminView({
      provider: "flock",
      loginEmail: "ops@example.com",
      passwordCiphertext: encryptSecret(password),
      updatedAt: new Date("2026-07-15T00:00:00.000Z"),
      isDeleted: false,
    });
    expect(view.email).toBe("ops@example.com");
    expect(view.password).toBe(password);
    expect(view.has_password).toBe(true);
  });

  it("已删除不回传账密", () => {
    const view = serializeProviderCredentialAdminView({
      provider: "mothership",
      loginEmail: "ops@example.com",
      passwordCiphertext: encryptSecret("x"),
      updatedAt: new Date(),
      isDeleted: true,
    });
    expect(view.email).toBeNull();
    expect(view.password).toBeNull();
    expect(view.has_password).toBe(false);
  });
});

describe("flock login context", () => {
  afterEach(() => {
    delete process.env.FLOCK_LOGIN_EMAIL;
    delete process.env.FLOCK_LOGIN_PASSWORD;
  });

  it("客户凭据优先于环境变量", async () => {
    process.env.FLOCK_LOGIN_EMAIL = "env@example.com";
    process.env.FLOCK_LOGIN_PASSWORD = "env-pass";
    await runWithFlockLoginContext(
      { email: "cust@example.com", password: "cust-pass" },
      "customer",
      async () => {
        expect(hasEffectiveFlockLogin()).toBe(true);
        expect(getFlockLoginSource()).toBe("customer");
      },
    );
  });

  it("无 ALS 时回退 env", async () => {
    process.env.FLOCK_LOGIN_EMAIL = "env@example.com";
    process.env.FLOCK_LOGIN_PASSWORD = "env-pass";
    expect(hasEffectiveFlockLogin()).toBe(true);
    expect(getFlockLoginSource()).toBe("env");
  });
});
