pragma yt.Pool = 'taxi-delivery';

$REQUESTS_HISTORY = '//home/taxi/testing/export/taxi-logistic-platform-production/requests_history';
$TRANSFERS_HISTRORY = '//home/taxi/testing/export/taxi-logistic-platform-production/planned_transfers_history';

$START_DATE = '2022-02-21';

$format = DateTime::Format('%Y-%m-%d %H:%M:%S%z');

select 
    created_at
    , employer_code
    , case when external_order_id is null then 1 else 0 end as external_order_id_null
    , request_code
    , r.request_id as request_id
    , operator_id
    , status
    , min_history_timestamp
    , external_order_id
from (
    SELECT 
        created_at,
        employer_code,
        request_id,
        request_code,
        max_by(status, history_event_id) as status
    from 
        range($REQUESTS_HISTORY, $START_DATE)
    where employer_code <> 'beru'
        -- and toDateTime(created_at) >= timestamp_sub(MINUTE, 60, now())
    group by created_at, employer_code, request_id, request_code
) as r
left join (
    select 
        request_id
        , operator_id
        , max(external_order_id) as external_order_id
        , $format(DateTime::FromSeconds(cast(min(if(external_order_id is not null, history_timestamp, null)) as Uint32))) as min_history_timestamp
    from 
        range($TRANSFERS_HISTRORY, $START_DATE)
    group by 
        request_id
        , operator_id
    having operator_id is not null
) as p 
on r.request_id = p.request_id
where 1=1
    and request_code in {request_codes};