{% set relevant_bank_transaction_status = "('AUTHORISED')" %}
{% set relevant_credit_note_status = "('AUTHORISED','PAID')" %}
{% set resolutions_credited_documents = "('ACCRECCREDIT')" %}

with
    int_xero__sales_denom_mart as (
        select * from {{ ref("int_xero__sales_denom_mart") }}
    ),
    int_xero__bank_transactions as (
        select * from {{ ref("int_xero__bank_transactions") }}
    ),
    int_xero__bank_transaction_line_items as (
        select * from {{ ref("int_xero__bank_transaction_line_items") }}
    ),
    int_xero__contacts as (select * from {{ ref("int_xero__contacts") }}),
    stg_seed__accounting_aggregations as (
        select *
        from {{ ref("stg_seed__accounting_aggregations") }}
        where root_aggregation = 'Host Resolutions Payments'
    )
select
    blt.id_line_item,
    'bank transaction' as document_class,
    blt.id_account,
    blt.account_code,
    blt.account_name,
    blt.line_description,
    bt.transaction_date_utc,
    bt.id_contact,
    xc.id_deal,
    blt.quantity,
    blt.unit_amount,
    blt.line_amount_local_curr,
    blt.line_amount_in_gbp,
    blt.line_amount_wo_taxes_local_curr,
    blt.line_amount_wo_taxes_in_gbp,
    blt.tax_amount_local_curr,
    blt.tax_amount_in_gbp,
    blt.transaction_currency_iso_4217
from int_xero__bank_transactions bt
inner join
    int_xero__bank_transaction_line_items blt
    on bt.id_bank_transaction = blt.id_bank_transaction
    and upper(bt.transaction_status) in {{ relevant_bank_transaction_status }}
left join int_xero__contacts xc on xc.id_contact = bt.id_contact
inner join stg_seed__accounting_aggregations aa on aa.account_code = blt.account_code
union all
select
    sdm.id_line_item,
    sdm.document_class,
    sdm.id_account,
    sdm.account_code,
    sdm.account_name,
    sdm.line_description,
    sdm.document_issued_date_utc,
    sdm.id_contact,
    sdm.id_deal,
    sdm.quantity,
    sdm.unit_amount,
    sdm.line_amount_local_curr,
    sdm.line_amount_in_gbp,
    sdm.line_amount_wo_taxes_local_curr,
    sdm.line_amount_wo_taxes_in_gbp,
    sdm.tax_amount_local_curr,
    sdm.tax_amount_in_gbp,
    sdm.document_currency_iso_4217
from int_xero__sales_denom_mart sdm
inner join stg_seed__accounting_aggregations aa on aa.account_code = sdm.account_code
where
    sdm.document_type in {{ resolutions_credited_documents }}
    and upper(sdm.document_status) in {{ relevant_credit_note_status }}
