PRAGMA query_only = ON;

-- Universo do Cruzeiro Novo.
SELECT
    l.listing_id,
    l.url,
    l.price_brl,
    l.condominium_brl,
    l.iptu_brl,
    l.area_m2,
    l.bedrooms,
    l.suites,
    l.parking_spaces,
    l.first_seen_at,
    l.last_seen_at,
    l.raw_html_path
FROM listings AS l
JOIN listing_searches AS s USING (listing_id)
WHERE instr(s.search_url, '/cruzeiro/novo/') > 0
  AND l.inactive_at IS NULL
ORDER BY l.price_brl, l.listing_id
LIMIT 100;

-- Cardinalidade de fotos por anúncio.
SELECT p.listing_id, COUNT(*) AS photo_count
FROM photos AS p
JOIN listing_searches AS s USING (listing_id)
WHERE instr(s.search_url, '/cruzeiro/novo/') > 0
  AND p.is_primary_gallery = 1
  AND EXISTS (
      SELECT 1 FROM listings AS l
      WHERE l.listing_id = p.listing_id AND l.inactive_at IS NULL
  )
GROUP BY p.listing_id
ORDER BY p.listing_id
LIMIT 100;

-- Número de estados históricos por anúncio.
SELECT h.listing_id, COUNT(*) AS snapshot_count
FROM listing_history AS h
JOIN listing_searches AS s USING (listing_id)
WHERE instr(s.search_url, '/cruzeiro/novo/') > 0
  AND EXISTS (
      SELECT 1 FROM listings AS l
      WHERE l.listing_id = h.listing_id AND l.inactive_at IS NULL
  )
GROUP BY h.listing_id
ORDER BY h.listing_id
LIMIT 100;
