-- Daily availability snapshots from Playtomic — slot-level pricing data.
-- One row per available 60-minute booking slot per court per venue per day.
-- "Available" = the slot was NOT booked at capture time. Missing slots = booked.
--
-- Reads morning snapshots and recheck files (JSONL format):
--   Morning:  availability_{date}.jsonl.gz              → snapshot_type = 'morning'
--   Recheck:  availability_{date}_recheck_{HH}.jsonl.gz → snapshot_type = 'recheck'
--
-- Only 60-min duration slots are kept (canonical hourly rate + occupancy unit).
-- Price parsed from strings like "14.56 EUR" or "48 GBP".
--
-- Source: data/landing/playtomic/{year}/{month}/availability_*.jsonl.gz

MODEL (
  name staging.stg_playtomic_availability,
  kind INCREMENTAL_BY_TIME_RANGE (
    time_column snapshot_date
  ),
  start '2026-03-01',
  cron '@daily',
  grain (snapshot_date, tenant_id, resource_id, slot_start_time, snapshot_type, captured_at_utc)
);

WITH
all_jsonl AS (
  SELECT
    CAST(date AS DATE)               AS snapshot_date,
    captured_at_utc,
    CASE
      WHEN filename LIKE '%_recheck_%' THEN 'recheck'
      ELSE 'morning'
    END                              AS snapshot_type,
    TRY_CAST(recheck_hour AS INTEGER) AS recheck_hour,
    tenant_id,
    slots                            AS slots_json
  FROM read_json(
    @LANDING_DIR || '/playtomic/*/*/availability_' || @start_ds || '*.jsonl.gz',
    format = 'newline_delimited',
    columns = {
      date: 'VARCHAR',
      captured_at_utc: 'VARCHAR',
      recheck_hour: 'VARCHAR',
      tenant_id: 'VARCHAR',
      slots: 'JSON'
    },
    filename = true
  )
  WHERE tenant_id IS NOT NULL
),
raw_resources AS (
  SELECT
    av.snapshot_date,
    av.captured_at_utc,
    av.snapshot_type,
    av.recheck_hour,
    av.tenant_id,
    resource_json
  FROM all_jsonl av,
  LATERAL UNNEST(
    from_json(av.slots_json, '["JSON"]')
  ) AS t(resource_json)
),
raw_slots AS (
  SELECT
    rr.snapshot_date,
    rr.captured_at_utc,
    rr.snapshot_type,
    rr.recheck_hour,
    rr.tenant_id,
    rr.resource_json ->> 'resource_id'                 AS resource_id,
    slot_json
  FROM raw_resources rr,
  LATERAL UNNEST(
    from_json(rr.resource_json -> 'slots', '["JSON"]')
  ) AS t(slot_json)
)
SELECT
  snapshot_date,
  tenant_id,
  resource_id,
  slot_json ->> 'start_time'                           AS slot_start_time,
  TRY_CAST(slot_json ->> 'duration' AS INTEGER)        AS duration_minutes,
  TRY_CAST(
    SPLIT_PART(slot_json ->> 'price', ' ', 1) AS DOUBLE
  )                                                    AS price_amount,
  SPLIT_PART(slot_json ->> 'price', ' ', 2)            AS price_currency,
  snapshot_type,
  recheck_hour,
  captured_at_utc
FROM raw_slots
WHERE resource_id IS NOT NULL
  AND (slot_json ->> 'start_time') IS NOT NULL
  AND TRY_CAST(slot_json ->> 'duration' AS INTEGER) = 60
