-- Individual court (resource) records from Playtomic venues.
-- Reads resources array from the landing zone to extract court type, size,
-- surface, and booking config.
--
-- Source: data/landing/playtomic/{year}/{month}/{day}/tenants.jsonl.gz

MODEL (
  name staging.stg_playtomic_resources,
  kind FULL,
  cron '@daily',
  grain (tenant_id, resource_id)
);

WITH
unnested AS (
  SELECT
    tenant_id,
    UPPER(address ->> 'country_code')                         AS country_code,
    UNNEST(from_json(resources, '["JSON"]'))                  AS resource_json
  FROM read_json(
    @LANDING_DIR || '/playtomic/*/*/*/tenants.jsonl.gz',
    format = 'newline_delimited',
    columns = {tenant_id: 'VARCHAR', address: 'JSON', resources: 'JSON'}
  )
  WHERE tenant_id IS NOT NULL
    AND resources IS NOT NULL
)
SELECT
  tenant_id,
  resource_json ->> 'resource_id'                             AS resource_id,
  country_code,
  NULLIF(TRIM(resource_json ->> 'name'), '')                  AS resource_name,
  resource_json ->> 'sport_id'                                AS sport_id,
  CASE WHEN LOWER(resource_json ->> 'is_active') IN ('true', '1')
    THEN TRUE ELSE FALSE END                                  AS is_active,
  LOWER(resource_json -> 'properties' ->> 'resource_type')    AS resource_type,
  LOWER(resource_json -> 'properties' ->> 'resource_size')    AS resource_size,
  LOWER(resource_json -> 'properties' ->> 'resource_feature') AS resource_feature,
  CASE WHEN LOWER(resource_json -> 'booking_settings' ->> 'is_bookable_online') IN ('true', '1')
    THEN TRUE ELSE FALSE END                                  AS is_bookable_online
FROM unnested
WHERE (resource_json ->> 'resource_id') IS NOT NULL
  AND (resource_json ->> 'sport_id') = 'PADEL'
QUALIFY ROW_NUMBER() OVER (PARTITION BY tenant_id, resource_json ->> 'resource_id' ORDER BY tenant_id) = 1
