import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

const SCRIPT_PATH = join(process.cwd(), "scripts", "record-priority1.sh");
const TS_SCRIPT_PATH = join(process.cwd(), "scripts", "record-priority1.ts");

const FORBIDDEN_PATTERNS = [
  /dashboard\.priority1\.com/i,
  /api\.priority1\.com/i,
];

function isForbiddenPriority1QuoteUrl(url: string): boolean {
  return FORBIDDEN_PATTERNS.some((pattern) => pattern.test(url));
}

describe("record-priority1.sh", () => {
  const content = readFileSync(SCRIPT_PATH, "utf8");

  it("存在且包含 headed 与 codegen 启动", () => {
    expect(content).toContain("RPA_HEADLESS=false");
    expect(content).toContain("playwright");
    expect(content).toContain("codegen");
  });

  it("禁止 Cabo 后台与 API 门户 URL", () => {
    expect(content).toContain("dashboard.priority1.com");
    expect(content).toContain("api.priority1.com");
    expect(content).toContain("check_url");
  });

  it("产出录制脚本与 storageState 路径", () => {
    expect(content).toContain(".rpa/recordings");
    expect(content).toContain("priority1-storage.json");
    expect(content).toContain("--save-storage");
  });
});

describe("record-priority1.ts (Windows 跨平台)", () => {
  const content = readFileSync(TS_SCRIPT_PATH, "utf8");

  it("存在且包含 headed codegen 与入口校验", () => {
    expect(content).toContain('RPA_HEADLESS: "false"');
    expect(content).toContain("playwright");
    expect(content).toContain("codegen");
    expect(content).toContain("isForbiddenPriority1QuoteUrl");
  });

  it("产出录制脚本与 storageState 路径", () => {
    expect(content).toContain(".rpa/recordings");
    expect(content).toContain("priority1-storage.json");
    expect(content).toContain("--save-storage");
  });

  it("默认打开公开询价页", () => {
    expect(content).toContain(
      "https://www.priority1.com/instant-freight-quotes/",
    );
  });
});

describe("isForbiddenPriority1QuoteUrl", () => {
  it("拒绝 Cabo 后台与 API 门户", () => {
    expect(
      isForbiddenPriority1QuoteUrl(
        "https://dashboard.priority1.com/account/login",
      ),
    ).toBe(true);
    expect(isForbiddenPriority1QuoteUrl("https://api.priority1.com/docs")).toBe(
      true,
    );
  });

  it("允许公开询价页与首页", () => {
    expect(
      isForbiddenPriority1QuoteUrl(
        "https://www.priority1.com/instant-freight-quotes/",
      ),
    ).toBe(false);
    expect(isForbiddenPriority1QuoteUrl("https://www.priority1.com/")).toBe(
      false,
    );
  });
});
