import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para Yaencontre (portal inmobiliario nacional)
 * URL: https://www.yaencontre.com/venta/pisos/{slug}
 * Paginación: /venta/pisos/{slug}/pagina-{N}.html
 */
export class YaencontreScraper extends BaseScraper {
    private readonly MAX_PAGES = 3;
    constructor() { super("https://www.yaencontre.com", "Yaencontre"); }

    async scrape(): Promise<Property[]> {
        const zones = await this.getActiveZones();
        const targets = zones.length > 0
            ? zones.map(z => z.slug)
            : ["lliria"];

        const properties: Property[] = [];
        const seenUrls = new Set<string>();
        let consecutiveBlocked = 0;

        for (const slug of targets) {
            const zone = zones.find(z => z.slug === slug);
            const zoneName = zone?.name ?? slug;

            for (let page = 1; page <= this.MAX_PAGES; page++) {
                const operationPath = this._operationType === "rent" ? "alquiler" : "venta";
                const url = page === 1
                    ? `${this.baseUrl}/${operationPath}/pisos/${slug}`
                    : `${this.baseUrl}/${operationPath}/pisos/${slug}/pagina-${page}.html`;

                const html = await this.fetchHtml(url);
                if (!html) {
                    if (page === 1) consecutiveBlocked++;
                    break;
                }
                consecutiveBlocked = 0; // reset al obtener contenido
                const $ = cheerio.load(html);

                let found = 0;
                $("[class*='property'], article, .listing-card, [class*='card'], [class*='HouseCard']").each((_i, el) => {
                    try {
                        const title = this.sanitizeText($(el).find("h2, h3, [class*='title'], [class*='Title']").first().text() || "Propiedad");
                        const priceRaw = $(el).find("[class*='price'], .precio, [class*='Price']").first().text();
                        const price = this.parsePrice(priceRaw);
                        const href = $(el).find("a[href]").first().attr("href") || "";
                        const url2 = href.startsWith("http") ? href : `${this.baseUrl}${href}`;
                        const location = this.sanitizeText($(el).find("[class*='location'], .ubicacion, [class*='address']").first().text());
                        const rooms = parseInt($(el).find("[class*='room'], [class*='hab']").first().text()) || 0;
                        const size_m2 = parseInt($(el).find("[class*='m2'], [class*='area']").first().text()) || 0;
                        const image_url = $(el).find("img").attr("src") || $(el).find("img").attr("data-src") || "";
                        if (price > 0 && href && !seenUrls.has(url2)) {
                            seenUrls.add(url2);
                            found++;
                            properties.push({
                                title, price, location: location || zoneName,
                                municipality: this.detectMunicipality(location + " " + zoneName, zones, zoneName),
                                property_type: this.normalizeType(title),
                                operation_type: this._operationType,
                                rooms, size_m2, url: url2, source: this.sourceName, image_url,
                            });
                        }
                    } catch { /* skip */ }
                });

                if (found < 3) break;
            }
            // Si 2 zonas consecutivas no devuelven nada → el portal está bloqueando, abortar
            if (consecutiveBlocked >= 2) {
                console.error(`[Yaencontre] Portal bloqueando sistemáticamente (${consecutiveBlocked} zonas sin respuesta), abortando scraping`);
                break;
            }
        }
        return this.validateResults(properties);
    }
}
