import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para Holprop (portal de propiedades en España)
 * URL correcta: https://www.holprop.com/sale/property/spain/valencia/lliria/
 * Nota: Llíria no tiene listados activos en Holprop (devuelve "NO PROPERTIES FOUND"),
 *       pero la URL es válida y el scraper funcionará si hay listados en el futuro.
 */
export class HolpropScraper extends BaseScraper {
    constructor() { super("https://www.holprop.com", "Holprop"); }

    async scrape(): Promise<Property[]> {
        const zones = await this.getActiveZones();
        const targets = zones.length > 0
            ? zones.map(z => `${this.baseUrl}/sale/property/spain/valencia/${z.slug}/`)
            : [`${this.baseUrl}/sale/property/spain/valencia/lliria/`];

        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, .property, [class*='property-item'], [class*='listing']").each((_i, el) => {
                try {
                    const title = this.sanitizeText($(el).find("h2, h3, [class*='title']").first().text() || "Property");
                    const priceRaw = $(el).find("[class*='price'], .price").first().text();
                    const price = this.parsePrice(priceRaw);
                    const href = $(el).find("a").attr("href") || "";
                    const url2 = href.startsWith("http") ? href : `${this.baseUrl}${href}`;
                    const location = this.sanitizeText($(el).find("[class*='location']").first().text());
                    const rooms = parseInt($(el).find("[class*='bed']").first().text()) || 0;
                    const size_m2 = parseInt($(el).find("[class*='m2'], [class*='size']").first().text()) || 0;
                    const image_url = $(el).find("img").attr("src") || "";
                    if (price > 0 && href && !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);
    }
}
