PRAGMA query_only = ON;

-- Universo capturado pela busca do Jardins Mangueiral.
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, '/jardins-mangueiral/') > 0
  AND l.inactive_at IS NULL
ORDER BY l.price_brl, l.listing_id
LIMIT 150;

-- Cardinalidade de fotos da galeria primária por anúncio; recomendações legadas são excluídas.
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, '/jardins-mangueiral/') > 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 150;

-- Número de snapshots por anúncio e cobertura temporal.
SELECT
    h.listing_id,
    COUNT(*) AS snapshot_count,
    MIN(h.captured_at) AS first_capture,
    MAX(h.captured_at) AS last_capture
FROM listing_history AS h
JOIN listing_searches AS s USING (listing_id)
WHERE instr(s.search_url, '/jardins-mangueiral/') > 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 150;

-- Campos ausentes no universo.
SELECT
    COUNT(*) AS listing_count,
    SUM(l.condominium_brl IS NULL) AS missing_condominium,
    SUM(l.iptu_brl IS NULL) AS missing_iptu,
    SUM(l.area_m2 IS NULL) AS missing_area,
    SUM(l.parking_spaces IS NULL) AS missing_parking
FROM listings AS l
JOIN listing_searches AS s USING (listing_id)
WHERE instr(s.search_url, '/jardins-mangueiral/') > 0
  AND l.inactive_at IS NULL
LIMIT 1;
