-- Intermediate model: Recursive predecessor mapping
-- Resolves academy conversion chains so historical data can be attributed
-- to the current (active) URN.

with recursive lineage as (
    -- Base: schools that are predecessors (linked via academy conversion, amalgamation, etc.)
    select
        urn,
        linked_urn as predecessor_urn,
        link_type,
        link_date,
        1 as depth
    from {{ ref('stg_gias_links') }}
    where link_type in (
        'Predecessor',
        'Predecessor - Loss of academy converter',
        'Predecessor - amalgamated',
        'Predecessor - Fresh Start'
    )

    union all

    -- Recursive step: follow the chain
    select
        l.urn,
        links.linked_urn as predecessor_urn,
        links.link_type,
        links.link_date,
        l.depth + 1
    from lineage l
    inner join {{ ref('stg_gias_links') }} links
        on l.predecessor_urn = links.urn
    where links.link_type in (
        'Predecessor',
        'Predecessor - Loss of academy converter',
        'Predecessor - amalgamated',
        'Predecessor - Fresh Start'
    )
    and l.depth < 5  -- safety limit
)

select
    urn as current_urn,
    predecessor_urn,
    link_type,
    link_date,
    depth
from lineage
