group BusinessAccount;

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

getAccountsCreatedOverTime() ::= <<
  select
    date(from_unixtime(created_date / 1000)) day
    -- TODO: use account_record_id, once populated
  , count(record_id) count
  from bac
  where <CHECK_TENANT()>
  group by 1
  order by 1
  ;
>>

getAccount(account_id) ::= <<
  select
    account_id
  , account_key
  , created_date
  , updated_date
  , balance
  , name
  , last_invoice_date
  , total_invoice_balance
  , last_payment_status
  , payment_method
  , credit_card_type
  , billing_address_country
  , currency
  , tenant_record_id
  from bac
  where account_id=:account_id
  <AND_CHECK_TENANT()>
  limit 1
  ;
>>

getAccountByKey(account_key) ::= <<
  select
    account_id
  , account_key
  , created_date
  , updated_date
  , balance
  , name
  , last_invoice_date
  , total_invoice_balance
  , last_payment_status
  , payment_method
  , credit_card_type
  , billing_address_country
  , currency
  , tenant_record_id
  from bac
  where account_key=:account_key
  <AND_CHECK_TENANT()>
  limit 1
  ;
>>

createAccount() ::= <<
  insert into bac(
    account_id
  , account_key
  , created_date
  , updated_date
  , balance
  , name
  , last_invoice_date
  , total_invoice_balance
  , last_payment_status
  , payment_method
  , credit_card_type
  , billing_address_country
  , currency
  , account_record_id
  , tenant_record_id
  ) values (
    :account_id
  , :account_key
  , :created_date
  , :updated_date
  , :balance
  , :name
  , :last_invoice_date
  , :total_invoice_balance
  , :last_payment_status
  , :payment_method
  , :credit_card_type
  , :billing_address_country
  , :currency
  , :accountRecordId
  , :tenantRecordId
  );
>>

saveAccount() ::= <<
  update bac set
    updated_date=:updated_date
  , balance=:balance
  , name=:name
  , last_invoice_date=:last_invoice_date
  , total_invoice_balance=:total_invoice_balance
  , last_payment_status=:last_payment_status
  , payment_method=:payment_method
  , credit_card_type=:credit_card_type
  , billing_address_country=:billing_address_country
  , currency=:currency
  where account_id=:account_id
  <AND_CHECK_TENANT()>
  ;
>>

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