with
    deal_attributes as (
        select *
        from {{ ref("int_kpis__dimension_deals") }}
        -- Exclude deals without live dates
        where effective_deal_start_date_utc is not null
    ),
    monthly_revenue_per_number_of_properties as (
        select
            date_trunc('month', m.date)::date as metric_month,
            coalesce(
                d.main_billing_country_iso_3_per_deal, 'global'
            ) as main_billing_country_iso_3,
            coalesce(
                d.hubspot_listing_segmentation, 'global'
            ) as hubspot_listing_segmentation,
            count(*) as deals_active_in_month,
            sum(coalesce(m.total_revenue_in_gbp, 0)) as total_revenue_in_gbp
        from {{ ref("int_monthly_aggregated_metrics_history_by_deal") }} m
        inner join
            deal_attributes d
            on m.id_deal = d.id_deal
            and date_trunc('month', m.date) >= d.effective_deal_start_month
            and date_trunc('month', m.date)
            <= coalesce(d.effective_deal_cancellation_month, '2099-01-01')
            and date_trunc('month', m.date)::date <> date_trunc('month', now())::date
        where d.hubspot_listing_segmentation <> 'UNSET'
        group by
            rollup (
                date_trunc('month', m.date)::date,
                d.hubspot_listing_segmentation,
                d.main_billing_country_iso_3_per_deal
            )
        having date_trunc('month', m.date)::date is not null
    )
select
    (r.metric_month - interval '1 day')::date as date,
    r.main_billing_country_iso_3,
    r.hubspot_listing_segmentation,
    sum(coalesce(m.total_revenue_in_gbp, 0)) as total_revenue_in_gbp,
    sum(m.deals_active_in_month) as total_active_months,
    sum(coalesce(m.total_revenue_in_gbp, 0))
    / sum(m.deals_active_in_month) as expected_mrr
from monthly_revenue_per_number_of_properties m
inner join
    monthly_revenue_per_number_of_properties r
    on r.metric_month > m.metric_month
    and r.metric_month <= m.metric_month + interval '12 months'
    and r.hubspot_listing_segmentation = m.hubspot_listing_segmentation
    and r.main_billing_country_iso_3 = m.main_billing_country_iso_3
group by r.metric_month, r.hubspot_listing_segmentation, r.main_billing_country_iso_3
