-- Staging model: Primary and secondary school admissions from EES
-- Wide format, one row per school per year. No geographic_level column.
-- Note: FSM_eligible_percent is stored with mixed case by target-postgres and
-- must be double-quoted in SQL to avoid case-folding to fsm_eligible_percent.

with source as (
    select * from {{ source('raw', 'ees_admissions') }}
    -- Exclude rows where school_urn is null, empty, or non-numeric (e.g. "n/a" LA aggregates)
    where school_urn ~ '^[0-9]+$'
      and time_period ~ '^[0-9]+$'
),

renamed as (
    select
        cast(trim(school_urn) as integer) as urn,
        cast(trim(time_period) as integer) as year,
        school_phase,
        entry_year,

        -- Places and offers
        {{ safe_numeric('total_number_places_offered') }}::integer as published_admission_number,
        {{ safe_numeric('number_preferred_offers') }}::integer as total_offers,
        {{ safe_numeric('number_1st_preference_offers') }}::integer as first_preference_offers,
        {{ safe_numeric('number_2nd_preference_offers') }}::integer as second_preference_offers,
        {{ safe_numeric('number_3rd_preference_offers') }}::integer as third_preference_offers,

        -- Applications
        {{ safe_numeric('times_put_as_any_preferred_school') }}::integer as total_applications,
        {{ safe_numeric('times_put_as_1st_preference') }}::integer as first_preference_applications,

        -- Proportions
        {{ safe_numeric('proportion_1stprefs_v_totaloffers') }} as first_preference_offer_pct,

        -- Derived: oversubscribed if 1st-preference applications > places offered
        -- Use already-cast columns to avoid repeating the regex expression
        (
            {{ safe_numeric('times_put_as_1st_preference') }}
            > {{ safe_numeric('total_number_places_offered') }}
        ) as oversubscribed,

        -- Context
        admissions_policy,
        {{ safe_numeric('"FSM_eligible_percent"') }} as fsm_eligible_pct

    from source
)

select * from renamed
