-- IMPORT
WITH users AS (
    SELECT * FROM {{ ref('stg_exchange__users') }}
),

user_email_verifications_group_by_user_ids AS (
    SELECT * FROM {{ ref('int_exchange__user_email_verifications_group_by_user_ids') }}
),

companies_brg_users AS (
    SELECT * FROM {{ ref('stg_exchange__companies_brg_users') }}
),


-- LOGIC
users_data_enrich AS (
    SELECT
        users.user_id,
        users.name,
        users.email,
        users.user_type,
        users.status    AS user_status,
        users.deleted_datetime  AS user_deleted_datetime,
        users.created_datetime  AS user_created_datetime,
        users.updated_datetime  AS user_updated_datetime,
        
        user_email_verifications_group_by_user_ids.is_completed  AS is_completed_email_verification,
        user_email_verifications_group_by_user_ids.number_of_verification_email_sent AS number_of_verification_email_sent,
        user_email_verifications_group_by_user_ids.first_email_verification_created_datetime,
        user_email_verifications_group_by_user_ids.last_email_verification_created_datetime,
        user_email_verifications_group_by_user_ids.email_verification_completed_datetime,
        
        companies_brg_users.company_id,
        '{{ modules.datetime.datetime.now(modules.pytz.timezone("Asia/Kuala_Lumpur")) }}' AS _dbt_ran_datetime
    
    FROM users

    LEFT JOIN user_email_verifications_group_by_user_ids
        ON (users.user_id = user_email_verifications_group_by_user_ids.user_id)

    LEFT JOIN companies_brg_users
        ON (users.user_id = companies_brg_users.user_id)
),

-- FINAL
final__dim_exchange__users AS (
    SELECT
        -- ids
        user_id,
        company_id,

        -- dimensions
        name,
        email,
        user_type,
        user_status,
        is_completed_email_verification,

        -- measures  
        number_of_verification_email_sent,

        -- date/times    
        user_deleted_datetime,
        user_created_datetime,
        user_updated_datetime,
        first_email_verification_created_datetime,
        last_email_verification_created_datetime,
        email_verification_completed_datetime,

        -- metadata
        _dbt_ran_datetime
    
    FROM users_data_enrich
)

SELECT * FROM final__dim_exchange__users