import { describe, expect, it } from "vitest";
import {
  isPickupDateAfterToday,
  minPickupDateDisplay,
  pickupDateValidationMessage,
} from "@/lib/priority1/pickup-date";
import { extractPriority1VisibleQuotes } from "@/workers/rpa/priority1/quote-extract";

const SAMPLE_SUMMARY = JSON.stringify({
  quote_id: 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,
});

describe("pickup date rules", () => {
  it("requires date strictly after today", () => {
    const min = minPickupDateDisplay();
    expect(min).toMatch(/^\d{2}\/\d{2}\/\d{4}$/);
    expect(pickupDateValidationMessage(min)).toBeNull();
    expect(isPickupDateAfterToday(min)).toBe(true);
  });

  it("rejects today or past dates", () => {
    const today = new Date();
    const mm = String(today.getMonth() + 1).padStart(2, "0");
    const dd = String(today.getDate()).padStart(2, "0");
    const yyyy = today.getFullYear();
    const todayDisplay = `${mm}/${dd}/${yyyy}`;
    expect(pickupDateValidationMessage(todayDisplay)).toBe("提货日须晚于今天");
  });
});

describe("parseVisibleQuoteCardsDom via extractPriority1VisibleQuotes", () => {
  const sampleDom = `
YOUR INSTANT QUOTE OPTIONS
QUOTE 1
STANDARD LTL
Estes
Transit: 1 Business Days
Quote Expiration Date: 07-09-2026
Estimated Delivery Date: 07-15-2026
$426.19
QUOTE 2
STANDARD LTL
TForce Freight
Transit: 2 Business Days
Quote Expiration Date: 07-09-2026
Estimated Delivery Date: 07-16-2026
$1703.90
`;

  it("无网络摘要时以可见 DOM 卡片为准", () => {
    const lines = extractPriority1VisibleQuotes([], sampleDom);
    expect(lines).toHaveLength(2);
    expect(lines[0]!.carrier).toBe("Estes");
    expect(lines[0]!.totalUsd).toBe(426.19);
    expect(lines[0]!.expirationDate).toBe("07/09/2026");
    expect(lines[0]!.deliveryDate).toBe("07/15/2026");
    expect(lines[1]!.totalUsd).toBe(1703.9);
  });

  it("DOM 无承运商时从 Feathery 摘要按 QUOTE 序号补全承运商与金额", () => {
    const dom = `
QUOTE 1
STANDARD LTL
Transit: 1 Business Days
Quote Expiration Date: 07-09-2026
Estimated Delivery Date: 07-15-2026
$999.99
QUOTE 2
STANDARD LTL
Transit: 2 Business Days
$888.88
`;
    const lines = extractPriority1VisibleQuotes([SAMPLE_SUMMARY], dom);
    expect(lines).toHaveLength(2);
    expect(lines[0]!.carrier).toBe("XPO");
    expect(lines[0]!.totalUsd).toBe(481.32);
    expect(lines[0]!.expirationDate).toBe("07/09/2026");
    expect(lines[1]!.carrier).toBe("Estes");
    expect(lines[1]!.totalUsd).toBe(503.68);
  });
});
