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 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 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 bii
where external_key = :external_key
<AND_CHECK_TENANT()>
order by created_date asc
;
>>

createInvoiceItem() ::= <<
insert into 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 bii where item_id = :item_id <AND_CHECK_TENANT()>;
>>

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

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