import * as cheerio from "cheerio";
import { Property } from "../types/property";
import { BaseScraper } from "./baseScraper";

/**
 * Scraper para Casasapo (portal de compra-venta de inmuebles en España)
 * Prueba múltiples tipos de propiedad por zona.
 */
export class CasasapoScraper extends BaseScraper {
    constructor() { super("https://www.casasapo.com", "Casasapo"); }

    async scrape(): Promise<Property[]> {
        const zones = await this.getActiveZones();
        const TYPES = ["piso", "casa", "chalet"];

        const targets: Array<{ url: string; zone: typeof zones[number] }> = [];
        if (zones.length > 0) {
            for (const z of zones) {
                for (const t of TYPES) {
                    targets.push({ url: `${this.baseUrl}/venta/${t}/municipio/${z.slug}/`, zone: z });
                }
            }
        } else {
            targets.push({ url: `${this.baseUrl}/venta/piso/municipio/lliria/`, zone: { name: "Llíria", slug: "lliria" } as any });
        }

        const properties: Property[] = [];
        const seenUrls = new Set<string>();

        for (const { url, zone } of targets) {
            const html = await this.fetchHtml(url);
            if (!html || html.length < 3000) continue; // Sin resultados o redir
            const $ = cheerio.load(html);
            $(".property, article, [class*='property'], [class*='listing'], [class*='anuncio']").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'], [class*='metros']").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: location || zone.name,
                            municipality: this.detectMunicipality(location || zone.name, zones, zone.name),
                            property_type: this.normalizeType(title),
                            rooms, size_m2, url: url2, source: this.sourceName, image_url,
                        });
                    }
                } catch { /* skip */ }
            });
        }
        return this.validateResults(properties);
    }
}
