{{ config(materialized="table", unique_key=["date", "id_deal"]) }}
with
    int_kpis__lifecycle_daily_accommodation as (
        select * from {{ ref("int_kpis__lifecycle_daily_accommodation") }}
    ),
    int_core__unique_accommodation_to_user as (
        select * from {{ ref("int_core__unique_accommodation_to_user") }}
    ),
    int_core__user_host as (select * from {{ ref("int_core__user_host") }}),

    active_accommodations_per_deal as (
        select
            al.date,
            uu.id_deal,
            sum(
                case when al.has_been_booked_within_last_12_months then 1 else 0 end
            ) as accommodations_booked_in_12_months
        from int_kpis__lifecycle_daily_accommodation al
        inner join
            int_core__unique_accommodation_to_user atu
            on al.id_accommodation = atu.id_accommodation
        inner join int_core__user_host uu on uu.id_user_host = atu.id_user_owner
        where uu.id_deal is not null
        group by 1, 2
    )
select
    date,
    id_deal,
    case
        when accommodations_booked_in_12_months = 0
        then '0'
        when accommodations_booked_in_12_months between 1 and 5
        then '01-05'
        when accommodations_booked_in_12_months between 6 and 20
        then '06-20'
        when accommodations_booked_in_12_months between 21 and 60
        then '21-60'
        when accommodations_booked_in_12_months >= 61
        then '61+'
    end as active_accommodations_per_deal_segmentation,
    accommodations_booked_in_12_months
from active_accommodations_per_deal
