-- Padel court locations from OpenStreetMap via Overpass API.
-- Reads landing zone JSON directly, unnests elements, filters to nodes with
-- valid coordinates, deduplicates on osm_id, and approximates country from bbox.
--
-- Source: data/landing/overpass/{year}/{month}/courts.json.gz

MODEL (
  name staging.stg_padel_courts,
  kind FULL,
  cron '@daily',
  grain osm_id
);

WITH parsed AS (
  SELECT
    elem ->> 'type'                     AS osm_type,
    (elem ->> 'id')::BIGINT             AS osm_id,
    TRY_CAST(elem ->> 'lat' AS DOUBLE)  AS lat,
    TRY_CAST(elem ->> 'lon' AS DOUBLE)  AS lon,
    elem -> 'tags' ->> 'name'           AS name,
    elem -> 'tags' ->> 'addr:country'   AS country_code,
    elem -> 'tags' ->> 'addr:city'      AS city_tag,
    elem -> 'tags' ->> 'addr:postcode'  AS postcode,
    elem -> 'tags' ->> 'operator'       AS operator_name,
    elem -> 'tags' ->> 'opening_hours'  AS opening_hours,
    elem -> 'tags' ->> 'fee'            AS fee,
    filename                            AS source_file,
    CURRENT_DATE                        AS extracted_date
  FROM (
    SELECT UNNEST(elements) AS elem, filename
    FROM read_json(
      @LANDING_DIR || '/overpass/*/*/courts.json.gz',
      format = 'auto',
      filename = true
    )
  )
  WHERE (elem ->> 'type') IS NOT NULL
),
deduped AS (
  SELECT *,
    ROW_NUMBER() OVER (PARTITION BY osm_id ORDER BY extracted_date DESC) AS rn
  FROM parsed
  WHERE osm_type = 'node'
    AND lat IS NOT NULL AND lon IS NOT NULL
    AND lat BETWEEN -90  AND 90
    AND lon BETWEEN -180 AND 180
),
with_country AS (
  SELECT
    osm_id, lat, lon,
    COALESCE(NULLIF(TRIM(UPPER(country_code)), ''),
             @infer_country_from_coords(lat, lon)) AS country_code,
    NULLIF(TRIM(name), '')    AS name,
    NULLIF(TRIM(city_tag), '') AS city,
    postcode, operator_name, opening_hours, fee, extracted_date
  FROM deduped
  WHERE rn = 1
)
SELECT
  osm_id,
  'osm'          AS source,
  lat, lon, country_code, name, city, postcode, operator_name, opening_hours,
  CASE LOWER(fee) WHEN 'yes' THEN TRUE WHEN 'no' THEN FALSE ELSE NULL END AS is_paid,
  extracted_date
FROM with_country
