import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para ERA Inmobiliaria España (franquicia ERA Real Estate)
 * URL: https://www.era.es/comprar/residencial/?localidad=lliria
 */
export class EraSpainScraper extends BaseScraper {
    constructor() { super("https://www.era.es", "ERA Spain"); }

    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}/comprar/residencial/?localidad=${encodeURIComponent(term)}`;
            const html = await this.fetchHtml(url);
            if (!html) continue;
            const $ = cheerio.load(html);
            $("article, .property, [class*='listing'], [class*='card']").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'], .municipio").first().text());
                    const rooms = parseInt($(el).find("[class*='hab'], [class*='room']").first().text()) || 0;
                    const size_m2 = parseInt($(el).find("[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);
    }
}
