import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

export class ThinkSpainScraper extends BaseScraper {
  constructor() { super("https://www.thinkspain.com", "ThinkSpain"); }

  async scrape(): Promise<Property[]> {
    const zones = await this.getActiveZones();
    // Usar thinkspain_slug si existe; si es null la zona no tiene página en ThinkSpain → omitir
    const fallbackZone = { name: 'Llíria', slug: 'lliria', thinkspain_slug: 'lliria' as string | null };
    const rawTargets = zones.length > 0
      ? zones.map(z => ({ tsSlug: (z.thinkspain_slug !== undefined ? z.thinkspain_slug : z.slug), zone: z }))
      : [{ tsSlug: 'lliria', zone: fallbackZone }];

    // Filtrar zonas sin slug ThinkSpain (null → no tienen listados)
    const targets = rawTargets.filter(t => !!t.tsSlug).map(t => ({
      slug: t.tsSlug as string,
      zone: t.zone,
    }));

    const properties: Property[] = [];
    const seenUrls = new Set<string>();

    for (const { slug, zone } of targets) {
      const pathCandidates = this._operationType === "rent"
        ? [
          `https://www.thinkspain.com/long-term-rentals/${slug}`,
          `https://www.thinkspain.com/property-to-rent-long-term/${slug}`,
          `https://www.thinkspain.com/rent-long-term/${slug}`,
        ]
        : [`${this.baseUrl}/property-for-sale/${slug}`];

      let html = "";
      for (const candidate of pathCandidates) {
        html = await this.fetchHtml(candidate);
        if (html && html.length > 2000) break;
      }
      if (!html || html.length < 2000) continue;
      const $ = cheerio.load(html);
      // ThinkSpain HTML: cada propiedad es un <article data-toggle-popup-url="/property-for-sale/ID">
      // Título en elemento con clase .property__title (link <a>)
      // Precio en primer elemento con clase que contenga "price"
      // URL en el atributo data-toggle-popup-url del <article>
      $("article[data-toggle-popup-url]").each((_i, el) => {
        // URL: extraer del atributo data-toggle-popup-url
        const popupPath = $(el).attr("data-toggle-popup-url") || "";
        const url2 = popupPath ? `${this.baseUrl}${popupPath}` : "";
        if (!url2) return;

        // Título: elemento con clase .property__title (primer <a> con el título)
        const rawTitle = $(el).find(".property__title").first().text().trim().split("\n")[0].trim();
        const title = this.sanitizeText(rawTitle || "Propiedad");

        // Precio: primer elemento con "price" en su clase
        const priceRaw = $(el).find("[class*='price']").first().text();
        const price = this.parsePrice(priceRaw);

        // Imagen: primer <img> (puede ser lazy con data-src)
        const imgEl = $(el).find("img").first();
        const image_url = imgEl.attr("src") || imgEl.attr("data-src") || "";

        if (price > 0 && !seenUrls.has(url2)) {
          seenUrls.add(url2);
          properties.push({
            title, price,
            location: zone.name,
            municipality: zone.name,
            property_type: this.normalizeType(title),
            operation_type: this._operationType,
            url: url2, source: this.sourceName, image_url,
          });
        }
      });
    }
    return this.validateResults(properties);
  }
}
