with
    int_xero__invoice_line_items as (
        select * from {{ ref("int_xero__invoice_line_items") }}
    ),
    int_xero__invoices as (select * from {{ ref("int_xero__invoices") }}),
    int_xero__credit_note_line_items as (
        select * from {{ ref("int_xero__credit_note_line_items") }}
    ),
    int_xero__credit_notes as (select * from {{ ref("int_xero__credit_notes") }})
select
    ili.id_invoice as id_document,
    ili.id_line_item as id_line_item,
    ili.id_item as id_item,
    'invoice' as document_type,
    ili.item_code as item_code,
    ili.quantity as quantity,
    ili.unit_amount as unit_amount,
    ili.line_amount_local_curr as line_amount_local_curr,
    ili.line_amount_in_gbp as line_amount_in_gbp,
    ili.line_amount_wo_taxes_local_curr,
    ili.line_amount_wo_taxes_in_gbp,
    ili.tax_amount_local_curr as tax_amount_local_curr,
    ili.tax_amount_in_gbp as tax_amount_in_gbp,
    ili.tax_type as tax_type,
    ili.invoice_currency_iso_4217 as invoice_currency_iso_4217,
    ili.line_description as line_description

from int_xero__invoice_line_items ili
left join int_xero__invoices i on i.id_invoice = ili.id_invoice

union all

select

    cnli.id_credit_note,
    cnli.id_line_item,
    cnli.id_item,
    'credit note' as document_type,
    cnli.item_code,
    cnli.quantity,
    cnli.unit_amount,
    -- We multiply all credit amounts by -1 so aggregations with
    -- invoicing side work the way you would expect them to
    cnli.line_amount_local_curr * -1,
    cnli.line_amount_in_gbp * -1,
    cnli.line_amount_wo_taxes_local_curr * -1,
    cnli.line_amount_wo_taxes_in_gbp * -1,
    cnli.tax_amount_local_curr * -1,
    cnli.tax_amount_in_gbp * -1,
    cnli.tax_type,
    cnli.credit_note_currency_iso_4217,
    cnli.line_description
from int_xero__credit_note_line_items cnli
left join int_xero__credit_notes cn on cn.id_credit_note = cnli.id_credit_note
