-- IMPORTS
WITH booking_logs AS (
    SELECT * FROM {{ ref('int_exchange__booking_logs_get_estimate_rates') }}
),


-- LOGICS
first_time_user_booking_id AS (
    SELECT 
        booking_id,
        user_id,
        created_at,
        row_number() OVER 
            (PARTITION BY booking_logs.user_id 
            ORDER BY booking_logs.created_at)                 AS cummulative_count_booking
    
    FROM
        booking_logs

    GROUP BY
        booking_id,
        user_id,
        created_at

    QUALIFY
        cummulative_count_booking = 1
),


first_time_company_booking_id AS (
    SELECT 
        booking_id,
        company_id,
        created_at,
        row_number() OVER 
            (PARTITION BY booking_logs.company_id 
            ORDER BY booking_logs.created_at)                 AS cummulative_count_booking
    
    FROM
        booking_logs

    GROUP BY
        booking_id,
        company_id,
        created_at

    QUALIFY
        cummulative_count_booking = 1
),


booking_logs_lists AS (
    SELECT 
        booking_logs.*,
        IFF(first_time_user_booking_id.booking_id IS NOT NULL, 1, 0)                            AS is_first_time_user,
        IFF(first_time_company_booking_id.booking_id IS NOT NULL, 1, 0)                         AS is_first_time_company  

    FROM
        booking_logs
    
    LEFT JOIN first_time_user_booking_id
        ON (booking_logs.booking_id = first_time_user_booking_id.booking_id)

    LEFT JOIN first_time_company_booking_id
        ON (booking_logs.booking_id = first_time_company_booking_id.booking_id)

    ORDER BY
        created_at
),


-- FINAL
final_fct_exchange__booking_logs AS (
    SELECT 
        *

    FROM booking_logs_lists
)

SELECT * FROM final_fct_exchange__booking_logs

