import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para Nuroa (meta-buscador inmobiliario internacional)
 * URL: https://www.nuroa.es/venta/valencia/lliria
 * Paginación: /venta/valencia/lliria?pagina=2
 */
export class NuroaScraper extends BaseScraper {
    private readonly MAX_PAGES = 3;
    constructor() { super("https://www.nuroa.es", "Nuroa"); }

    async scrape(): Promise<Property[]> {
        const zones = await this.getActiveZones();
        const targets = zones.length > 0
            ? zones.map(z => ({ baseUrl: `${this.baseUrl}/venta/valencia/${z.slug}`, zone: z }))
            : [{ baseUrl: `${this.baseUrl}/venta/valencia/lliria`, zone: { name: "Llíria", slug: "lliria" } as any }];

        const properties: Property[] = [];
        const seenUrls = new Set<string>();

        for (const { baseUrl, zone } of targets) {
            for (let page = 1; page <= this.MAX_PAGES; page++) {
                const url = page === 1 ? baseUrl : `${baseUrl}?pagina=${page}`;
                const html = await this.fetchHtml(url);
                if (!html) break;
                const $ = cheerio.load(html);

                let found = 0;
                $("article, .listing, [class*='property'], [class*='listing-card'], [class*='result']").each((_i, el) => {
                    try {
                        const title = this.sanitizeText($(el).find("h2, h3, [class*='title']").first().text() || "Propiedad");
                        const priceRaw = $(el).find("[class*='price'], .precio").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()) || zone.name;
                        const rooms = parseInt($(el).find("[class*='room'], [class*='bedroom']").first().text()) || 0;
                        const size_m2 = parseInt($(el).find("[class*='size'], [class*='m2']").first().text()) || 0;
                        const image_url = $(el).find("img").attr("src") || "";
                        if (price > 0 && href && !seenUrls.has(url2)) {
                            seenUrls.add(url2);
                            found++;
                            properties.push({
                                title, price, location,
                                municipality: zone.name, // zona ya filtrada en URL
                                property_type: this.normalizeType(title),
                                rooms, size_m2, url: url2, source: this.sourceName, image_url,
                            });
                        }
                    } catch { /* skip */ }
                });

                if (found < 3) break; // Sin más resultados
            }
        }
        return this.validateResults(properties);
    }
}
