group BusinessInvoiceItem;

CHECK_TENANT(prefix) ::= "<prefix>tenant_record_id = :tenantRecordId"
AND_CHECK_TENANT(prefix) ::= "AND <CHECK_TENANT(prefix)>"

getInvoiceItem(item_id) ::= <<
select
  item_id
, created_date
, updated_date
, invoice_id
, item_type
, external_key
, product_name
, product_type
, product_category
, slug
, phase
, billing_period
, start_date
, end_date
, amount
, currency
, linked_item_id
, tenant_record_id
from old_bii
where item_id = :item_id
<AND_CHECK_TENANT()>
limit 1
;
>>

getInvoiceItemsForInvoice(invoice_id) ::= <<
select
  item_id
, created_date
, updated_date
, invoice_id
, item_type
, external_key
, product_name
, product_type
, product_category
, slug
, phase
, billing_period
, start_date
, end_date
, amount
, currency
, linked_item_id
, tenant_record_id
from old_bii
where invoice_id = :invoice_id
<AND_CHECK_TENANT()>
order by created_date asc
;
>>

getInvoiceItemsForBundleByKey(external_key) ::= <<
select
  item_id
, created_date
, updated_date
, invoice_id
, item_type
, external_key
, product_name
, product_type
, product_category
, slug
, phase
, billing_period
, start_date
, end_date
, amount
, currency
, linked_item_id
, tenant_record_id
from old_bii
where external_key = :external_key
<AND_CHECK_TENANT()>
order by created_date asc
;
>>

createInvoiceItem() ::= <<
insert into old_bii (
  item_id
, created_date
, updated_date
, invoice_id
, item_type
, external_key
, product_name
, product_type
, product_category
, slug
, phase
, billing_period
, start_date
, end_date
, amount
, currency
, linked_item_id
, account_record_id
, tenant_record_id
) values (
  :item_id
, :created_date
, :updated_date
, :invoice_id
, :item_type
, :external_key
, :product_name
, :product_type
, :product_category
, :slug
, :phase
, :billing_period
, :start_date
, :end_date
, :amount
, :currency
, :linked_item_id
, :accountRecordId
, :tenantRecordId
);
>>

deleteInvoiceItem(item_id) ::= <<
delete from old_bii where item_id = :item_id <AND_CHECK_TENANT()>;
>>

deleteInvoiceItemsForAccount(account_id) ::= <<
delete from old_bii where old_bii.invoice_id in (select invoice_id from old_bin where old_bin.account_id = :account_id <AND_CHECK_TENANT("old_bin.")> for update) <AND_CHECK_TENANT("old_bii.")>;
>>

test() ::= <<
select 1 from old_bii where <CHECK_TENANT()> limit 1;
>>
