import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para Engel & Völkers España (inmobiliaria premium)
 * URL: https://www.engelvoelkers.com/es/search/?q=lliria&businessArea=residential&sortOrder=DESC&sortField=sortPrice&pageIndex=0&businessLine=2&language=es_ES&country=ESP&contractType=buy
 */
export class EngelVolkersScraper extends BaseScraper {
    constructor() { super("https://www.engelvoelkers.com", "Engel & Völkers"); }

    async scrape(): Promise<Property[]> {
        const zones = await this.getActiveZones();
        const searchTerms = zones.length > 0 ? zones.map(z => z.name) : ["llíria"];

        const properties: Property[] = [];
        const seenUrls = new Set<string>();

        for (const term of searchTerms) {
            const url = `${this.baseUrl}/es/search/?q=${encodeURIComponent(term)}&businessArea=residential&sortField=sortPrice&contractType=buy&language=es_ES&country=ESP`;
            const html = await this.fetchHtml(url);
            if (!html) continue;
            const $ = cheerio.load(html);
            $("[class*='ev-property'], [class*='property-card'], article").each((_i, el) => {
                try {
                    const title = this.sanitizeText($(el).find("h2, h3, [class*='title']").first().text() || "Propiedad");
                    const priceRaw = $(el).find("[class*='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'], [class*='address']").first().text());
                    const rooms = parseInt($(el).find("[class*='room'], [class*='bedroom']").first().text()) || 0;
                    const size_m2 = parseInt($(el).find("[class*='area'], [class*='m2']").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 + " " + term, zones),
                            property_type: this.normalizeType(title),
                            rooms, size_m2, url: url2, source: this.sourceName, image_url,
                        });
                    }
                } catch { /* skip */ }
            });
        }
        return this.validateResults(properties);
    }
}
