import { describe, expect, it } from "vitest";
import {
  extractPriority1AllApiQuotes,
  extractPriority1QuotesFromDomText,
  extractPriority1QuotesFromNetworkBodies,
  extractPriority1VisibleQuotes,
  isPriority1ManualFollowupPage,
  isPriority1QuotePageReady,
  parseFtlCalendarQuotes,
  PRIORITY1_MANUAL_FOLLOWUP_MESSAGE,
  resolvePriority1SubmitOutcome,
} from "@/workers/rpa/priority1/quote-extract";

const SAMPLE_API = JSON.stringify({
  data: {
    id: 42830001,
    rateQuotes: [
      {
        id: 1,
        carrierName: "XPO",
        carrierCode: "XPOL",
        transitDays: 8,
        deliveryDate: "2026-07-13T00:00:00",
        expirationDate: "2026-06-27T07:00:30Z",
        serviceLevelDescription: "Standard Rate",
        rateQuoteDetail: { total: 481.32 },
      },
      {
        id: 2,
        carrierName: "Estes",
        carrierCode: "EXLA",
        transitDays: 5,
        rateQuoteDetail: { total: 503.68 },
      },
      {
        id: 3,
        carrierName: "Hidden Carrier",
        carrierCode: "HIDN",
        transitDays: 4,
        rateQuoteDetail: { total: 999.99 },
      },
    ],
  },
});

const SAMPLE_SUMMARY = JSON.stringify({
  quote_id: 42830001,
  cabo_url: "https://dashboard.priority1.com/ltl/quotes/details/42830001",
  LTL_best_price_quote_carrier: "XPO",
  LTL_best_price_quote_cost: "481.32",
  LTL_best_price_quote_transit: 8,
  LTL_second_rate_quote_carrier: "Estes",
  LTL_second_rate_quote_cost: "503.68",
  LTL_second_rate_quote_transit: 5,
});

const SAMPLE_DOM = `
QUOTE 1 Forward $560.27 STANDARD LTL Forward Quote Expiration Date 07-03-2026
2 Business Days
QUOTE 2 Go2 Logistics $2052.67 STANDARD LTL Go2 Logistics Quote Expiration Date
3 Business Days
`;

describe("priority1 quote-extract", () => {
  it("全量 API 解析 rateQuotes", () => {
    const lines = extractPriority1AllApiQuotes([SAMPLE_API]);
    expect(lines.length).toBe(3);
    expect(lines[0].carrier).toBe("XPO");
    expect(lines[0].source).toBe("api-all");
  });

  it("同时有 API 与摘要时优先页面可见摘要", () => {
    const lines = extractPriority1VisibleQuotes([SAMPLE_API, SAMPLE_SUMMARY]);
    expect(lines.length).toBe(2);
    expect(lines[0].carrier).toBe("XPO");
    expect(lines[0].source).toBe("feathery-summary");
  });

  it("无摘要时回退 feathery 摘要字段", () => {
    const lines = extractPriority1QuotesFromNetworkBodies([SAMPLE_SUMMARY]);
    expect(lines.length).toBe(2);
    expect(lines[1].carrier).toBe("Estes");
  });

  it("解析 QUOTE 卡片 DOM", () => {
    const lines = extractPriority1QuotesFromDomText(SAMPLE_DOM);
    expect(lines.length).toBe(2);
    expect(lines[0].carrier).toBe("Forward");
    expect(lines[0].totalUsd).toBe(560.27);
    expect(lines[0].source).toBe("visible-dom");
  });

  it("解析 FTL 日历表格报价（无 $ 前缀）", () => {
    const dom = `
YOUR INSTANT QUOTE OPTIONS
SHIPPING DETAILS From 32801 To 28202 Weight 15000 lb
Wed 1 1652.16 Thu 2 1652.16 Fri 3 1650.78
Mon 6 2178.47 Tue 7 1652.16
REQUEST A NEW QUOTE BOOK NOW IN CABO TMS
`;
    expect(isPriority1QuotePageReady(dom)).toBe(true);
    const lines = parseFtlCalendarQuotes(dom);
    expect(lines.length).toBe(5);
    expect(lines[0].source).toBe("ftl-calendar");
    expect(lines[0].deliveryDate).toBe("DAY:1");
    expect(lines[3].deliveryDate).toBe("DAY:6");
    expect(lines.some((q) => q.totalUsd === 2178.47)).toBe(true);
  });

  it("识别 MORE INFORMATION NEEDED 人工跟进页", () => {
    const dom = `
MORE INFORMATION NEEDED
A Priority1 freight specialist will reach out to confirm the missing details
Confirm Details & Lock In Your Rate
REQUEST NEW QUOTE
`;
    expect(isPriority1ManualFollowupPage(dom)).toBe(true);
    const resolved = resolvePriority1SubmitOutcome([], dom);
    expect(resolved.outcome).toBe("manual_followup");
    expect(resolved.message).toBe(PRIORITY1_MANUAL_FOLLOWUP_MESSAGE);
    expect(resolved.quotes).toHaveLength(0);
  });
});
