/*
 * VUActivity DRIVER_ACTIVITY extraction for the bytebar tachograph schema.
 *
 * Real join path:
 *   VUActivity -> VUDailyActivity -> VUInstallation -> VehicleIdentification
 * Optional driver/card context comes from VUActivity.ID_IWCycle -> IWCycle -> Card.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
CandidateActivity as (
    select
        va.ID,
        va.BeginTime,
        activity_time.EndTime,
        va.Activity,
        va.Slot,
        va.CardStatus,
        va.DrivingStatus,
        va.ID_FileLog,
        va.ID_IWCycle,
        vda.RecordDate,
        vda.ID_FileLog as vda_filelog_id,
        vui.ID_VehicleIdentification,
        vui.ID_FileLog as vui_filelog_id,
        vi.ID as vehicle_identification_id,
        vi.VIN as vehicle_vin,
        coalesce(va.ID_FileLog, vda.ID_FileLog, vui.ID_FileLog) as file_log_id
    from dbo.VUActivity va
    join dbo.VUDailyActivity vda on vda.ID = va.ID_VUDailyActivity
    join dbo.VUInstallation vui on vui.ID = vda.ID_VUInstallation
    join dbo.VehicleIdentification vi on vi.ID = vui.ID_VehicleIdentification
    cross apply (values (dateadd(minute, coalesce(va.Duration, 0), va.BeginTime))) activity_time(EndTime)
    where (:occurredTo is null or va.BeginTime < :occurredTo)
      and (
          :occurredFrom is null
          or va.BeginTime >= :occurredFrom
          or activity_time.EndTime >= :occurredFrom
      )
)
,
CandidateVehicle as (
    select
        va.ID,
        va.BeginTime,
        va.EndTime,
        va.Activity,
        va.Slot,
        va.CardStatus,
        va.DrivingStatus,
        va.ID_FileLog,
        va.ID_IWCycle,
        va.RecordDate,
        va.vda_filelog_id,
        va.ID_VehicleIdentification,
        va.vui_filelog_id,
        va.vehicle_identification_id,
        va.vehicle_vin,
        va.file_log_id,
        v.ID as vehicle_registration_id,
        v.ID_Nation as vehicle_registration_nation_id,
        v.VRN as vehicle_registration_number
    from CandidateActivity va
    outer apply (
        select top 1 vehicle.ID,
                     vehicle.VRN,
                     vehicle.ID_Nation
        from dbo.Vehicle vehicle
        where vehicle.ID_VehicleIdentification = va.vehicle_identification_id
          and (vehicle.ValidFrom is null or vehicle.ValidFrom <= va.BeginTime)
          and (vehicle.ValidTo is null or vehicle.ValidTo > va.BeginTime)
        order by
            vehicle.ValidFrom desc,
            vehicle.ID desc
    ) v
    where (
          :organisationId is null
          or exists (
              select 1
              from dbo.Vehicle_I_90021 rel
              join OrgTree on OrgTree.I_90021_OID = rel.ID_I_90021
              where rel.ID_Vehicle = v.ID
                and rel.GILT_BIS is null
          )
      )
)
,
Base as (
    select
        va.ID,
        va.BeginTime,
        va.EndTime,
        va.Activity,
        va.Slot,
        va.CardStatus,
        va.DrivingStatus,
        va.ID_FileLog,
        va.vda_filelog_id,
        va.vui_filelog_id,

        coalesce(fl.DownloadDate, fl.OriginalDownloadDate, fl.TStamp, fl.CreationDate) as received_partner_at,
        coalesce(fl.ID, va.ID_FileLog, va.vda_filelog_id, va.vui_filelog_id) as source_package_id_raw,
        coalesce(fl.ID_VehicleIdentification, va.ID_VehicleIdentification) as source_package_entity_id_raw,
        coalesce(fl.DownloadFrom, va.RecordDate) as source_package_period_from,
        coalesce(fl.DownloadTo, dateadd(day, 1, va.RecordDate)) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at,

        null as odometer_m,
        c.ID_Driver as driver_id,
        cn.AlphaCode as driver_card_nation,
        c.CardNumber as driver_card_number,
        va.vehicle_identification_id,
        va.vehicle_registration_id,
        va.vehicle_vin,
        vn.AlphaCode as vehicle_registration_nation,
        va.vehicle_registration_number
    from CandidateVehicle va
    left join dbo.FileLog fl on fl.ID = va.file_log_id
    left join dbo.Nation vn on vn.ID = va.vehicle_registration_nation_id
    left join dbo.IWCycle iw on iw.ID = va.ID_IWCycle
    left join dbo.Card c on c.ID = iw.ID_Card
    left join dbo.Nation cn on cn.ID = c.ID_Nation
)
,
Extracted as (
select
    cast(base.ID as varchar(128)) as source_row_id,
    concat('TACHOGRAPH:VU_ACTIVITY:', base.ID, ':', evt.lifecycle) as external_source_event_id,

    evt.occurred_at as occurred_at,
    base.received_partner_at,
    base.Activity as activity_code,
    case upper(coalesce(base.Activity, ''))
        when 'DRIVING' then 'DRIVE'
        when 'DRIVE' then 'DRIVE'
        when 'WORK' then 'WORK'
        when 'AVAILABILITY' then 'AVAILABILITY'
        when 'AVAILABLE' then 'AVAILABILITY'
        when 'BREAK_REST' then 'BREAK_REST'
        when 'BREAK/REST' then 'BREAK_REST'
        when 'REST' then 'BREAK_REST'
        else 'UNKNOWN_ACTIVITY'
    end as event_type,
    evt.lifecycle as lifecycle,
    base.Slot as card_slot,
    base.CardStatus as card_status,
    base.DrivingStatus as driving_status,
    base.odometer_m,

    cast(base.driver_id as varchar(128)) as driver_source_entity_id,
    base.driver_card_nation,
    base.driver_card_number,

    cast(base.vehicle_identification_id as varchar(128)) as vehicle_source_entity_id,
    base.vehicle_vin,
    cast(base.vehicle_registration_id as varchar(128)) as vehicle_registration_source_entity_id,
    base.vehicle_registration_nation,
    base.vehicle_registration_number,

    'VEHICLE_UNIT' as source_package_kind,
    cast(base.source_package_id_raw as varchar(128)) as source_package_id,
    base.source_package_id_raw as source_package_sort_id,
    cast(base.source_package_entity_id_raw as varchar(128)) as source_package_entity_id,
    base.source_package_period_from,
    base.source_package_period_to,
    base.source_package_imported_at
from Base base
cross apply (values
    ('START', base.BeginTime),
    ('END', base.EndTime)
) evt(lifecycle, occurred_at)
where (:occurredFrom is null or evt.occurred_at >= :occurredFrom)
  and (:occurredTo is null or evt.occurred_at < :occurredTo)
/*
 * Organisation filter: vehicle membership in GetOrganisationTree(null, :organisationId, 0, null).
 */
)
select *
from Extracted extracted
where (
      :sourcePackageWatermarkEnabled = 0
      or :lastSourcePackageImportedAt is null
      or extracted.source_package_imported_at is null
      or extracted.source_package_imported_at > :lastSourcePackageImportedAt
      or (
          extracted.source_package_imported_at = :lastSourcePackageImportedAt
          and (
              :lastSourcePackageIdNumeric is null
              or extracted.source_package_sort_id is null
              or extracted.source_package_sort_id > :lastSourcePackageIdNumeric
          )
      )
)
