with int_xero__invoices as (select * from {{ ref("int_xero__invoices") }})

select
    i.id_invoice,
    j.id_line_item,
    j.id_item,
    j.item_code,
    j.quantity,
    j.unit_amount,
    j.line_amount,
    j.tax_amount,
    j.tax_type,
    j.line_description
from int_xero__invoices i
cross join
    lateral(
        select
            (jsonb_array_elements(i.line_items) ->> 'LineItemID') as id_line_item,
            (jsonb_array_elements(i.line_items) -> 'Item') ->> 'ItemID' as id_item,
            (jsonb_array_elements(i.line_items) -> 'Item') ->> 'Code' as item_code,
            (jsonb_array_elements(i.line_items) -> 'Item') ->> 'Name' as item_name,
            (jsonb_array_elements(i.line_items) ->> 'Quantity') as quantity,
            (jsonb_array_elements(i.line_items) ->> 'UnitAmount') as unit_amount,
            (jsonb_array_elements(i.line_items) ->> 'LineAmount') as line_amount,
            (jsonb_array_elements(i.line_items) ->> 'TaxAmount') as tax_amount,
            (jsonb_array_elements(i.line_items) ->> 'TaxType') as tax_type,
            (jsonb_array_elements(i.line_items) ->> 'Description') as line_description
    ) j
