import { describe, it, expect } from "vitest";
import { buildBuyTicketUrl, escapeHtml } from "./buyTicketUrl.js";

describe("buildBuyTicketUrl", () => {
  it("builds a URL with the correct base", () => {
    const url = buildBuyTicketUrl("MOW", "LED", "20260501");
    expect(url.startsWith("https://www.aeroflot.ru/sb/app/ru-ru#/search?")).toBe(true);
  });

  it("includes the routes triple dep.date.arr", () => {
    const url = buildBuyTicketUrl("MOW", "LED", "20260501");
    expect(url).toContain("routes=MOW.20260501.LED");
  });

  it("includes the stable UTM and adults/cabin params", () => {
    const url = buildBuyTicketUrl("MOW", "LED", "20260501");
    expect(url).toContain("adults=1");
    expect(url).toContain("cabin=economy");
    expect(url).toContain("autosearch=Y");
    expect(url).toContain("utm_source=aflwebbot");
  });

  // TZ §4.1.24.6 R48: when Дата рейса is not set, the transition to SB must
  // be performed without a date ("переход в SB должен выполнятся без даты").
  it("4.1.24-R48: omits date segment when date is undefined", () => {
    const url = buildBuyTicketUrl("MOW", "LED", undefined);
    // Must not contain a date segment — format is {dep}.{arr}, not {dep}.{date}.{arr}
    expect(url).toContain("routes=MOW.LED");
    // Verify no phantom "." before "LED" from a missing date
    expect(url).not.toMatch(/routes=MOW\.\d{8}\.LED/);
  });

  it("4.1.24-R46: CTA opens in new tab via target=_blank (link in popup HTML)", () => {
    // buildBuyTicketUrl itself produces the URL; the caller sets target="_blank".
    // This test verifies the URL is well-formed for embedding in anchor hrefs.
    const url = buildBuyTicketUrl("SVO", "AER", "20260601");
    expect(url).toMatch(/^https:\/\/www\.aeroflot\.ru\/sb\/app\/ru-ru#\/search\?/);
  });

  it("4.1.24-R47: URL includes all required fixed SB params", () => {
    const url = buildBuyTicketUrl("MOW", "LED", "20260501");
    expect(url).toContain("adults=1");
    expect(url).toContain("cabin=economy");
    expect(url).toContain("children=0");
    expect(url).toContain("infants=0");
    expect(url).toContain("autosearch=Y");
  });
});

describe("escapeHtml", () => {
  it("escapes &, <, >, and double-quote", () => {
    expect(escapeHtml("A & B < C > D \"E\"")).toBe(
      "A &amp; B &lt; C &gt; D &quot;E&quot;",
    );
  });

  it("returns the input unchanged when no special chars", () => {
    expect(escapeHtml("Москва")).toBe("Москва");
  });
});
