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

export class IdealistaScraper extends BaseScraper {
  constructor() {
    super("https://www.idealista.com", "Idealista");
  }

  async scrape(): Promise<Property[]> {
    const zones = await this.getActiveZones();
    // Idealista usa slug-provincia/municipio — para zonas de Valencia funciona bien
    const targets = zones.length > 0
      ? zones.map(z => `${this.baseUrl}/venta-viviendas/${z.slug}-valencia/municipio/`)
      : [`${this.baseUrl}/venta-viviendas/lliria-valencia/municipio/`];

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

    for (const url of targets) {
      const html = await this.fetchHtml(url);
      if (!html) continue;
      const $ = cheerio.load(html);
      $("article.item").each((_i, el) => {
        try {
          const title = this.sanitizeText($(el).find(".item-link").attr("title") || $(el).find("a.item-link").text());
          const priceRaw = this.sanitizeText($(el).find(".item-price").text());
          const price = this.parsePrice(priceRaw);
          const location = this.sanitizeText($(el).find(".item-detail-char").first().text());
          const href = $(el).find("a.item-link").attr("href") || "";
          const url2 = href.startsWith("http") ? href : `${this.baseUrl}${href}`;
          const rooms = parseInt($(el).find(".item-detail").eq(0).text()) || 0;
          const size_m2 = parseInt($(el).find(".item-detail").eq(1).text()) || 0;
          const image_url = $(el).find("img").attr("src") || "";
          if (price > 0 && title && !seenUrls.has(url2)) {
            seenUrls.add(url2);
            properties.push({
              title, price, location,
              municipality: this.detectMunicipality(location, zones),
              property_type: this.normalizeType(title),
              rooms, size_m2, url: url2,
              source: this.sourceName, image_url,
            });
          }
        } catch { /* skip */ }
      });
    }
    return this.validateResults(properties);
  }
}
