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

export class FotocasaScraper extends BaseScraper {
  constructor() {
    super("https://www.fotocasa.es", "Fotocasa");
  }

  async scrape(): Promise<Property[]> {
    const zones = await this.getActiveZones();
    const targets = zones.length > 0
      ? zones.map(z => `${this.baseUrl}/es/comprar/viviendas/${z.slug}-valencia/todas-las-zonas/l`)
      : [`${this.baseUrl}/es/comprar/viviendas/lliria-valencia/todas-las-zonas/l`];

    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);
      $('[class*="re-Card"]').each((_i, el) => {
        try {
          const title = this.sanitizeText($(el).find('[class*="re-Card-title"]').text() || $(el).find("h3").text() || "Propiedad");
          const priceRaw = this.sanitizeText($(el).find('[class*="re-Card-price"]').text() || $(el).find('[class*="Price"]').text());
          const price = this.parsePrice(priceRaw);
          const location = this.sanitizeText($(el).find('[class*="re-Card-location"]').text());
          const href = $(el).find("a").attr("href") || "";
          const url2 = href.startsWith("http") ? href : `${this.baseUrl}${href}`;
          const rooms = parseInt($(el).find('[class*="Bedroom"]').text()) || 0;
          const size_m2 = parseInt($(el).find('[class*="Surface"]').text()) || 0;
          const image_url = $(el).find("img").attr("src") || "";
          const category = $(el).find('[class*="re-Card-typology"], [class*="typology"]').text();
          if (price > 0 && !seenUrls.has(url2)) {
            seenUrls.add(url2);
            properties.push({
              title, price, location,
              municipality: this.detectMunicipality(location, zones),
              property_type: this.normalizeType(title, category),
              rooms, size_m2, url: url2,
              source: this.sourceName, image_url,
            });
          }
        } catch { /* skip */ }
      });
    }
    return this.validateResults(properties);
  }
}

