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

getNextBusEventEntries() ::= <<
    select
      record_id
      , class_name
      , event_json
      , user_token
      , created_date
      , creating_owner
      , processing_owner
      , processing_available_date
      , processing_state
      , account_record_id
      , tenant_record_id
    from bus_events
    where
      processing_state != 'PROCESSED'
      and processing_state != 'REMOVED'
      and (processing_owner IS NULL OR processing_available_date \<= :now)
    order by
      record_id asc
    limit :max
    ;
>>


claimBusEvent() ::= <<
    update bus_events
    set
      processing_owner = :owner
      , processing_available_date = :nextAvailable
      , processing_state = 'IN_PROCESSING'
    where
      record_id = :recordId
      and processing_state != 'PROCESSED'
      and processing_state != 'REMOVED'
      and (processing_owner IS NULL OR processing_available_date \<= :now)
    ;
>>

clearBusEvent() ::= <<
    update bus_events
    set
      processing_state = 'PROCESSED'
    where
      record_id = :recordId
    ;
>>

removeBusEventsById() ::= <<
    update bus_events
    set
      processing_state = 'REMOVED'
    where
      record_id = :recordId
    ;
>>


insertBusEvent() ::= <<
    insert into bus_events (
      class_name
    , event_json
    , user_token
    , created_date
    , creating_owner
    , processing_owner
    , processing_available_date
    , processing_state
    , account_record_id
    , tenant_record_id
    ) values (
      :className
    , :eventJson
    , :userToken
    , :createdDate
    , :creatingOwner
    , :processingOwner
    , :processingAvailableDate
    , :processingState
    , :accountRecordId
    , :tenantRecordId
    );
>>

insertClaimedHistory() ::= <<
    insert into claimed_bus_events (
          owner_id
        , claimed_date
        , bus_event_id
        , account_record_id
        , tenant_record_id
      ) values (
          :ownerId
        , :claimedDate
        , :busEventId
        , :accountRecordId
        , :tenantRecordId
      );
>>
