WITH container_packing_lists AS (
    SELECT * FROM {{ ref('base_shipping__container_packing_lists') }}
),

containers AS (
    SELECT * FROM {{ ref('base_shipping__containers') }}
),

packing_lists AS (
    SELECT * FROM {{ ref('base_shipping__packing_lists') }}
),

packages AS (
    SELECT * FROM {{ ref('base_shipping__packages') }}
),

company_modules AS (
    SELECT * FROM {{ ref('base_shipping__company_modules') }}
),

company_connections AS (
    SELECT * FROM {{ ref('base_shipping__company_connections') }}
),

orders AS (
    SELECT * FROM {{ ref('base_shipping__orders') }}
)
-- LOGIC
company_module_join_companies AS (
    SELECT 
        company_modules.id                    AS company_id,
        company_modules.name                  AS company_name,
        company_connections.invitee_reference AS marking
    
    FROM 
        company_modules
    LEFT JOIN company_connections 
        ON (company_modules.id = company_connections.invitee_id) 
),

final AS (
    SELECT 
        container_packing_lists.*,
        containers.*,
        packing_lists.*,
        packages.*,
        packages.created_at     AS packages_created_at,
        ((packages.width/100) * (packages.height/100) * (packages.length/100) * packages.quantity) as cbm

    FROM container_packing_lists

    JOIN containers
        ON (container_packing_lists.container_id = containers.id)
    JOIN packing_lists 
        ON (container_packing_lists.packing_list_id = packing_lists.id)
    JOIN packages 
        ON (packages.packing_list_id = packing_lists.id and packages.deleted_at is null) 

    WHERE packing_lists.deleted_at is null  AND packages_created_at >= '2022-01-01')
-- ),

-- final_group_by_company_module AS (
--     SELECT 
--         final.owner_id,
--         SUM(final.cbm)          AS life_time_cbm
    
--     FROM final
    
--     GROUP BY
--         owner_id
-- )



SELECT * FROM final

-- SELECT
--             containers.*, packing_lists.id as packing_list_id, SUM((packages.width/100) * (packages.height/100) * (packages.length/100) * packages.quantity) as cbm
--         FROM
--             container_packing_lists as packed_containers
--          JOIN containers ON packed_containers.container_id = containers.id
--         	JOIN packing_lists ON packed_containers.packing_list_id = packing_lists.id
--         	JOIN packages ON (packages.packing_list_id = packing_lists.id and packages.deleted_at is null) 
--         WHERE packing_lists.deleted_at is null GROUP BY packing_lists.id;