-- Mart: Toronto Market Summary
-- Aggregated view combining purchase and rental market indicators
-- Grain: One row per year-month

with purchases_agg as (
    select
        year,
        month,
        month_name,
        quarter,

        -- Aggregate purchase metrics across all districts
        sum(sales_count) as total_sales,
        sum(dollar_volume) as total_dollar_volume,
        round(avg(avg_price), 0) as avg_price_all_districts,
        round(avg(median_price), 0) as median_price_all_districts,
        sum(new_listings) as total_new_listings,
        sum(active_listings) as total_active_listings,
        round(avg(days_on_market), 0) as avg_days_on_market,
        round(avg(sale_to_list_ratio), 2) as avg_sale_to_list_ratio,
        round(avg(absorption_rate), 3) as avg_absorption_rate,
        round(avg(months_of_inventory), 1) as avg_months_of_inventory,
        round(avg(avg_price_yoy_pct), 2) as avg_price_yoy_pct

    from {{ ref('mart_toronto_purchases') }}
    group by year, month, month_name, quarter
),

rentals_agg as (
    select
        year,

        -- Aggregate rental metrics across all zones (all bedroom types)
        round(avg(avg_rent), 0) as avg_rent_all_zones,
        round(avg(vacancy_rate), 2) as avg_vacancy_rate,
        round(avg(rent_change_pct), 2) as avg_rent_change_pct,
        sum(rental_universe) as total_rental_universe

    from {{ ref('mart_toronto_rentals') }}
    group by year
),

final as (
    select
        p.year,
        p.month,
        p.month_name,
        p.quarter,

        -- Purchase market indicators
        p.total_sales,
        p.total_dollar_volume,
        p.avg_price_all_districts,
        p.median_price_all_districts,
        p.total_new_listings,
        p.total_active_listings,
        p.avg_days_on_market,
        p.avg_sale_to_list_ratio,
        p.avg_absorption_rate,
        p.avg_months_of_inventory,
        p.avg_price_yoy_pct,

        -- Rental market indicators (annual, so join on year)
        r.avg_rent_all_zones,
        r.avg_vacancy_rate,
        r.avg_rent_change_pct,
        r.total_rental_universe,

        -- Affordability indicator (price to rent ratio)
        case
            when r.avg_rent_all_zones > 0
            then round(p.avg_price_all_districts / (r.avg_rent_all_zones * 12), 1)
            else null
        end as price_to_annual_rent_ratio

    from purchases_agg p
    left join rentals_agg r on p.year = r.year
)

select * from final
order by year desc, month desc
