import { describe, expect, it } from "vitest";
import {
  buildFlockAliasedEmail,
  createFreshFlockTestAccount,
  createRandomQqEmail,
  createVerifiedQqAliasedEmail,
  parseFlockEnvPool,
} from "@/lib/flock/fresh-account";

describe("parseFlockEnvPool", () => {
  it("解析逗号与换行分隔", () => {
    expect(parseFlockEnvPool("a@b.com, c@d.com\ne@f.com")).toEqual([
      "a@b.com",
      "c@d.com",
      "e@f.com",
    ]);
  });
});

describe("createRandomQqEmail", () => {
  it("1/2/3 开头 + 9 位数字 @qq.com", () => {
    for (let i = 0; i < 20; i += 1) {
      const email = createRandomQqEmail();
      expect(email).toMatch(/^[123]\d{9}@qq\.com$/);
    }
  });
});

describe("createVerifiedQqAliasedEmail", () => {
  it("已验证 QQ + 短别名", () => {
    const email = createVerifiedQqAliasedEmail();
    expect(email).toMatch(/^3457189488\+[a-f0-9]{6}@qq\.com$/);
  });
});

describe("buildFlockAliasedEmail", () => {
  it("Gmail 使用 + 子地址", () => {
    const email = buildFlockAliasedEmail("user@gmail.com", "abc123");
    expect(email).toMatch(/^user\+[a-z0-9]+@gmail\.com$/);
  });

  it("QQ 基址使用短 + 别名", () => {
    const email = buildFlockAliasedEmail("3457189488@qq.com", "x1y2z3");
    expect(email).toMatch(/^3457189488\+[a-z0-9]+@qq\.com$/);
  });
});

describe("createFreshFlockTestAccount", () => {
  it("默认使用已验证 QQ 短别名（非虚构号码）", () => {
    const prev = {
      pool: process.env.FLOCK_EMAIL_POOL,
      alias: process.env.FLOCK_EMAIL_ALIAS_BASE,
      test: process.env.FLOCK_TEST_EMAIL,
      mode: process.env.FLOCK_EMAIL_MODE,
    };
    delete process.env.FLOCK_EMAIL_POOL;
    delete process.env.FLOCK_EMAIL_ALIAS_BASE;
    delete process.env.FLOCK_TEST_EMAIL;
    delete process.env.FLOCK_EMAIL_MODE;

    const a = createFreshFlockTestAccount();
    expect(a.email).toMatch(/^3457189488\+[a-z0-9]+@qq\.com$/);

    process.env.FLOCK_EMAIL_POOL = prev.pool;
    process.env.FLOCK_EMAIL_ALIAS_BASE = prev.alias;
    process.env.FLOCK_TEST_EMAIL = prev.test;
    process.env.FLOCK_EMAIL_MODE = prev.mode;
  });

  it("使用邮箱池时不重复编造域名", () => {
    const prev = process.env.FLOCK_EMAIL_POOL;
    process.env.FLOCK_EMAIL_POOL = "one@gmail.com,two@outlook.com";
    const a = createFreshFlockTestAccount();
    expect(["one@gmail.com", "two@outlook.com"]).toContain(a.email);
    process.env.FLOCK_EMAIL_POOL = prev;
  });
});
