-- Raw Playtomic venue (tenant) listings from unauthenticated tenant search API.
-- Source: data/landing/playtomic/{year}/{month}/tenants.json.gz
-- Format: {"tenants": [{tenant_id, name, address, sport_ids, ...}], "count": N}

MODEL (
  name padelnomics.raw_playtomic_tenants,
  kind FULL,
  cron '@daily',
  grain tenant_id
);

SELECT
  tenant ->> 'tenant_id'                                AS tenant_id,
  tenant ->> 'tenant_name'                              AS tenant_name,
  tenant -> 'address' ->> 'street'                      AS street,
  tenant -> 'address' ->> 'city'                        AS city,
  tenant -> 'address' ->> 'postal_code'                 AS postal_code,
  tenant -> 'address' ->> 'country_code'                AS country_code,
  TRY_CAST(tenant -> 'address' ->> 'coordinate_lat' AS DOUBLE) AS lat,
  TRY_CAST(tenant -> 'address' ->> 'coordinate_lon' AS DOUBLE) AS lon,
  tenant ->> 'sport_ids'                                AS sport_ids_raw,
  tenant ->> 'tenant_type'                              AS tenant_type,
  filename                                              AS source_file,
  CURRENT_DATE                                          AS extracted_date
FROM (
  SELECT
    UNNEST(tenants) AS tenant,
    filename
  FROM read_json(
    @LANDING_DIR || '/playtomic/*/*/tenants.json.gz',
    format = 'auto',
    filename = true
  )
)
WHERE (tenant ->> 'tenant_id') IS NOT NULL
