import { afterEach, describe, expect, it } from "vitest";
import {
  getFlockLoginUrl,
  hasFlockLoginCredentials,
  isFlockFreshSessionPerQuote,
  isFlockRandomAccountPerQuote,
  shouldSaveFlockStorageState,
} from "@/lib/flock/env";
import {
  flockLoginRegistrationBlockedMessage,
  isFlockLoginPage,
  resetFlockLoginSessionFlagForTests,
} from "@/workers/rpa/flock/login";
import { shouldRotateFlockSession } from "@/workers/rpa/flock/worker-session";

describe("Flock login credentials env", () => {
  const prev = {
    email: process.env.FLOCK_LOGIN_EMAIL,
    password: process.env.FLOCK_LOGIN_PASSWORD,
    fresh: process.env.FLOCK_FRESH_SESSION_PER_QUOTE,
    random: process.env.FLOCK_RANDOM_ACCOUNT_PER_QUOTE,
    loginUrl: process.env.FLOCK_LOGIN_URL,
  };

  afterEach(() => {
    process.env.FLOCK_LOGIN_EMAIL = prev.email;
    process.env.FLOCK_LOGIN_PASSWORD = prev.password;
    process.env.FLOCK_FRESH_SESSION_PER_QUOTE = prev.fresh;
    process.env.FLOCK_RANDOM_ACCOUNT_PER_QUOTE = prev.random;
    process.env.FLOCK_LOGIN_URL = prev.loginUrl;
  });

  it("无凭据时 hasCredentials=false", () => {
    delete process.env.FLOCK_LOGIN_EMAIL;
    delete process.env.FLOCK_LOGIN_PASSWORD;
    expect(hasFlockLoginCredentials()).toBe(false);
  });

  it("成对凭据时开启登录门禁并关闭 fresh/random", () => {
    process.env.FLOCK_LOGIN_EMAIL = "user@example.com";
    process.env.FLOCK_LOGIN_PASSWORD = "secret";
    process.env.FLOCK_FRESH_SESSION_PER_QUOTE = "true";
    process.env.FLOCK_RANDOM_ACCOUNT_PER_QUOTE = "true";
    expect(hasFlockLoginCredentials()).toBe(true);
    expect(isFlockFreshSessionPerQuote()).toBe(false);
    expect(isFlockRandomAccountPerQuote()).toBe(false);
    expect(shouldSaveFlockStorageState()).toBe(true);
  });

  it("默认登录 URL", () => {
    delete process.env.FLOCK_LOGIN_URL;
    expect(getFlockLoginUrl()).toContain("flockfreight.com/login");
  });
});

describe("isFlockLoginPage", () => {
  it("识别 login URL", () => {
    expect(
      isFlockLoginPage({
        url: () => "https://app.flockfreight.com/login",
      } as never),
    ).toBe(true);
    expect(
      isFlockLoginPage({
        url: () => "https://app.flockfreight.com/get-a-quote",
      } as never),
    ).toBe(false);
  });
});

describe("login mode session rotation", () => {
  afterEach(() => {
    delete process.env.FLOCK_LOGIN_EMAIL;
    delete process.env.FLOCK_LOGIN_PASSWORD;
    resetFlockLoginSessionFlagForTests();
  });

  it("有登录凭据时禁止换号", () => {
    process.env.FLOCK_LOGIN_EMAIL = "a@b.com";
    process.env.FLOCK_LOGIN_PASSWORD = "x";
    expect(
      shouldRotateFlockSession(
        "FLOCK_ACCOUNT_REJECTED: We had an issue creating your account",
      ),
    ).toBe(false);
  });

  it("注册页阻断文案", () => {
    expect(flockLoginRegistrationBlockedMessage()).toContain("登录凭据");
  });
});
