-- Eurostat SDMX city codelist: city_code → city_name mapping.
-- Maps coded identifiers (e.g. DE001C) to human-readable names (e.g. Berlin).
-- This is the bridge table that lets stg_population join to dim_cities.
--
-- Source: data/landing/eurostat_city_labels/{year}/{month}/cities_codelist.json.gz

MODEL (
  name staging.stg_city_labels,
  kind FULL,
  cron '@daily',
  grain city_code
);

WITH raw AS (
  SELECT unnest(rows) AS r
  FROM read_json(
    @LANDING_DIR || '/eurostat_city_labels/*/*/cities_codelist.json.gz',
    auto_detect = true
  )
)
SELECT
  UPPER(TRIM(r ->> 'city_code'))          AS city_code,
  TRIM(r ->> 'city_name')                 AS city_name,
  -- Country code is always the first two letters of the city code (e.g. DE001C → DE)
  UPPER(LEFT(TRIM(r ->> 'city_code'), 2)) AS country_code,
  CURRENT_DATE                            AS extracted_date
FROM raw
WHERE (r ->> 'city_code') IS NOT NULL
  AND (r ->> 'city_name') IS NOT NULL
  AND LENGTH(TRIM(r ->> 'city_code')) > 0
  AND LENGTH(TRIM(r ->> 'city_name')) > 0
