"""Shared query helpers for listing data.""" from app.config import settings from app.schemas import ListingResponse LISTING_SELECT = f""" SELECT l.global_id, l.tiny_id, l.url, l.title, l.city, l.postcode, l.province, l.neighbourhood, l.municipality, l.latitude, l.longitude, l.object_type, l.house_type, l.offering_type, l.construction_type, l.construction_year, l.energy_label, l.living_area, l.plot_area, l.bedrooms, l.rooms, l.has_garden, l.has_balcony, l.has_solar_panels, l.has_heat_pump, l.has_roof_terrace, l.is_energy_efficient, l.is_monument, l.current_price, l.status, l.price_per_sqm, l.publication_date, COALESCE(r.elo_rating, {settings.DEFAULT_ELO}) AS elo_rating, COALESCE(r.comparison_count, 0) AS comparison_count, COALESCE(r.wins, 0) AS wins, COALESCE(r.losses, 0) AS losses FROM {settings.LISTINGS_SCHEMA}.{settings.LISTINGS_TABLE} l LEFT JOIN {settings.ELO_SCHEMA}.ratings r ON l.global_id = r.global_id """ def row_to_listing(row) -> ListingResponse: """Convert a raw SQL row to a ListingResponse.""" return ListingResponse( global_id=row.global_id, tiny_id=row.tiny_id, url=row.url, title=row.title, city=row.city, postcode=row.postcode, province=row.province, neighbourhood=row.neighbourhood, municipality=row.municipality, latitude=float(row.latitude) if row.latitude is not None else None, longitude=float(row.longitude) if row.longitude is not None else None, object_type=row.object_type, house_type=row.house_type, offering_type=row.offering_type, construction_type=row.construction_type, construction_year=row.construction_year, energy_label=row.energy_label, living_area=row.living_area, plot_area=row.plot_area, bedrooms=row.bedrooms, rooms=row.rooms, has_garden=row.has_garden, has_balcony=row.has_balcony, has_solar_panels=row.has_solar_panels, has_heat_pump=row.has_heat_pump, has_roof_terrace=row.has_roof_terrace, is_energy_efficient=row.is_energy_efficient, is_monument=row.is_monument, current_price=row.current_price, status=row.status, price_per_sqm=float(row.price_per_sqm) if row.price_per_sqm is not None else None, publication_date=row.publication_date, elo_rating=round(float(row.elo_rating), 1), comparison_count=int(row.comparison_count), wins=int(row.wins), losses=int(row.losses), )