-- IMPORTS
WITH bookings AS (
    SELECT * FROM {{ ref('int_exchange__bookings_get_estimate_rates') }}
),


-- LOGICS
bookings_lists AS (
    SELECT 
        bookings.*,

        CASE 
            WHEN ROW_NUMBER() OVER (PARTITION BY bookings.company_id ORDER BY bookings.booking_created_datetime) = 1 THEN 1 
            ELSE 0 
        END AS is_first_time_company,

        CASE 
            WHEN bookings.status = '3' 
                AND 
                MIN(IFF(bookings.status = '3', bookings.booking_created_datetime, NULL))
                    OVER (PARTITION BY bookings.company_id) 
                    = bookings.booking_created_datetime 
            THEN 1
            ELSE 0 
        END AS is_first_time_company_completed,


        CASE 
            WHEN ROW_NUMBER() OVER (PARTITION BY bookings.user_id ORDER BY bookings.booking_created_datetime) = 1 THEN 1 
            ELSE 0 
        END AS is_first_time_user,

        CASE 
            WHEN bookings.status = '3' 
                AND 
                MIN(IFF(bookings.status = '3', bookings.booking_created_datetime, NULL))
                    OVER (PARTITION BY bookings.user_id) 
                    = bookings.booking_created_datetime 
            THEN 1
            ELSE 0 
        END AS is_first_time_user_completed
    
    FROM
        bookings

    ORDER BY
        booking_created_datetime
),


-- FINAL
final_fct_exchange__bookings AS (
    SELECT 
        *

    FROM bookings_lists
)

SELECT * FROM final_fct_exchange__bookings

