/** Helpers shared by store adapters. */
import type { Cheerio } from "cheerio";
import type { AnyNode } from "domhandler";

/** An offer without a positive finite price has nothing to compare on — drop it. */
export function validPrice(priceEur: number): boolean {
  return Number.isFinite(priceEur) && priceEur > 0;
}

/**
 * Image URL from a lazy-loading <img>: the real URL sits in data-srcset (first
 * entry) on the autoteile-net-family stores; `fallbackAttr` names where this
 * store keeps it when there is no srcset ("src" or "data-src").
 */
export function lazyImageUrl(
  img: Cheerio<AnyNode>,
  fallbackAttr: "src" | "data-src",
): string | null {
  return img.attr("data-srcset")?.split(" ")[0] ?? img.attr(fallbackAttr) ?? null;
}

/**
 * Stock flag from a Latvian storefront availability text, for HTML stores that
 * expose nothing structured: "Nav noliktavā" / "Nav pieejams" mean out of stock,
 * any other present text means in stock, absent text means unknown.
 */
export function inStockFromText(availability: string | null): boolean | null {
  if (!availability) return null;
  return !/^nav\b/i.test(availability.trim());
}
