import fixture from "../../fixtures/partsale/W71252.html";
import ic24Fixture from "../../fixtures/ic24/W71252.html";
import { createEngine } from "../../src/engine.js";
import { MemoryResponseCache } from "../../src/core/memoryCache.js";
import type { BrowserFetcher, PoliteFetcher } from "../../src/core/types.js";

declare global {
  interface Window {
    phaseCResult?: unknown;
  }
}

const http: PoliteFetcher = {
  get: async () => fixture,
  postForm: async () => { throw new Error("unexpected POST form"); },
  postJson: async () => { throw new Error("unexpected POST JSON"); },
};
let ic24Url = "";
const browser: BrowserFetcher = {
  fetchJson: async () => { throw new Error("unexpected browser JSON fetch"); },
  fetchOriginHtml: async (_storeId, _homepage, url) => {
    ic24Url = url;
    return ic24Fixture;
  },
  fetchPageHtml: async () => { throw new Error("unexpected browser page fetch"); },
};

void run();

async function run(): Promise<void> {
  try {
    const engine = createEngine({ http, browser, cache: new MemoryResponseCache() });
    const response = await engine.search("partsale", "W 712/52");
    if (!response.ok || response.offers.length === 0 || response.query !== "W71252") {
      throw new Error("fixture search returned an unexpected response");
    }
    const ic24Response = await engine.search("ic24", "W 712/52");
    if (!ic24Response.ok || ic24Response.offers.length === 0 || !ic24Url.endsWith("/detalas/search=VzcxMjUy")) {
      throw new Error("IC24 browser-runtime fixture search returned an unexpected response");
    }
    window.phaseCResult = {
      ok: true,
      store: response.store,
      query: response.query,
      offerCount: response.offers.length,
      ic24OfferCount: ic24Response.offers.length,
    };
    document.body.dataset["state"] = "passed";
  } catch (error) {
    window.phaseCResult = { ok: false, error: error instanceof Error ? error.message : String(error) };
    document.body.dataset["state"] = "failed";
  }
}
