-- Venue opening hours by day of week from Playtomic.
-- Unpivots the opening_hours struct into one row per (tenant_id, day_of_week).
-- Used downstream to calculate total weekly/daily capacity hours.
--
-- DuckDB auto-infers opening_hours as STRUCT, so we access each day by literal
-- key (no dynamic access) and UNION ALL to unpivot.
--
-- Source: data/landing/playtomic/{year}/{month}/{day}/tenants.jsonl.gz

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

WITH
venues AS (
  SELECT
    tenant_id,
    opening_hours AS oh
  FROM read_json(
    @LANDING_DIR || '/playtomic/*/*/*/tenants.jsonl.gz',
    format = 'newline_delimited',
    columns = {tenant_id: 'VARCHAR', opening_hours: 'JSON'}
  )
  WHERE tenant_id IS NOT NULL
    AND opening_hours IS NOT NULL
),
-- Unpivot by UNION ALL — 7 literal key accesses
unpivoted AS (
  SELECT tenant_id, 'MONDAY'    AS day_of_week, 1 AS day_number,
    oh -> 'MONDAY'    ->> 'opening_time' AS opening_time,
    oh -> 'MONDAY'    ->> 'closing_time' AS closing_time
  FROM venues
  UNION ALL
  SELECT tenant_id, 'TUESDAY'   AS day_of_week, 2,
    oh -> 'TUESDAY'   ->> 'opening_time',
    oh -> 'TUESDAY'   ->> 'closing_time'
  FROM venues
  UNION ALL
  SELECT tenant_id, 'WEDNESDAY' AS day_of_week, 3,
    oh -> 'WEDNESDAY' ->> 'opening_time',
    oh -> 'WEDNESDAY' ->> 'closing_time'
  FROM venues
  UNION ALL
  SELECT tenant_id, 'THURSDAY'  AS day_of_week, 4,
    oh -> 'THURSDAY'  ->> 'opening_time',
    oh -> 'THURSDAY'  ->> 'closing_time'
  FROM venues
  UNION ALL
  SELECT tenant_id, 'FRIDAY'    AS day_of_week, 5,
    oh -> 'FRIDAY'    ->> 'opening_time',
    oh -> 'FRIDAY'    ->> 'closing_time'
  FROM venues
  UNION ALL
  SELECT tenant_id, 'SATURDAY'  AS day_of_week, 6,
    oh -> 'SATURDAY'  ->> 'opening_time',
    oh -> 'SATURDAY'  ->> 'closing_time'
  FROM venues
  UNION ALL
  SELECT tenant_id, 'SUNDAY'    AS day_of_week, 7,
    oh -> 'SUNDAY'    ->> 'opening_time',
    oh -> 'SUNDAY'    ->> 'closing_time'
  FROM venues
)
SELECT
  tenant_id,
  day_of_week,
  day_number,
  opening_time,
  closing_time,
  -- Hours open this day (e.g., 09:00 to 23:00 = 14.0h)
  ROUND(
    (EXTRACT(HOUR FROM closing_time::TIME) + EXTRACT(MINUTE FROM closing_time::TIME) / 60.0)
    - (EXTRACT(HOUR FROM opening_time::TIME) + EXTRACT(MINUTE FROM opening_time::TIME) / 60.0)
  , 2) AS hours_open
FROM unpivoted
WHERE opening_time IS NOT NULL
  AND closing_time IS NOT NULL
QUALIFY ROW_NUMBER() OVER (PARTITION BY tenant_id, day_of_week ORDER BY tenant_id) = 1
