/*
 * CardActivity DRIVER_ACTIVITY extraction for the bytebar tachograph schema.
 *
 * Real join path:
 *   CardActivity -> CardDailyActivity -> Card -> Driver/Nation
 *
 * CardActivity itself has no direct vehicle reference. The OUTER APPLY resolves
 * the best matching CardVehiclesUsed row for the activity timestamp when one is
 * available.
 */
select
    cast(ca.ID as varchar(128)) as source_row_id,
    cast(ca.ID as varchar(128)) as card_activity_id,
    concat('TACHOGRAPH:CARD_ACTIVITY:', ca.ID) as external_source_event_id,

    ca.BeginTime as occurred_at,
    cast(null as datetime) as received_partner_at,
    ca.Activity as activity_code,
    ca.Activity as activity_text,
    case upper(coalesce(ca.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,
    'SNAPSHOT' as lifecycle,
    ca.Slot as card_slot,
    ca.CardStatus as card_status,
    ca.DrivingStatus as driving_status,
    cast(null as bigint) as odometer_m,

    cast(d.ID as varchar(128)) as driver_source_entity_id,
    cn.AlphaCode as driver_card_nation,
    c.CardNumber as driver_card_number,

    cast(coalesce(cvu.ID_Vehicle, v.ID) as varchar(128)) as vehicle_source_entity_id,
    coalesce(cvu.VIN, vi.VIN) as vehicle_vin,
    vn.AlphaCode as vehicle_registration_nation,
    v.VRN as vehicle_registration_number,

    'DRIVER_CARD' as source_package_kind,
    cast(coalesce(ca.ID_FileLog, cda.ID_FileLog, c.ID_FileLog) as varchar(128)) as source_package_id,
    cast(c.ID as varchar(128)) as source_package_entity_id,
    cda.RecordDate as source_package_period_from,
    coalesce(cda.RecordDateTo, dateadd(day, 1, cda.RecordDate)) as source_package_period_to,
    cast(null as datetime) as source_package_imported_at
from dbo.CardActivity ca
join dbo.CardDailyActivity cda on cda.ID = ca.ID_DailyActivity
join dbo.Card c on c.ID = cda.ID_Card
left join dbo.Driver d on d.ID = c.ID_Driver
left join dbo.Nation cn on cn.ID = c.ID_Nation
outer apply (
    select top 1 used.ID_Vehicle,
                 used.VIN,
                 used.OdoBegin,
                 used.ID_VUInstallation
    from dbo.CardVehiclesUsed used
    where used.ID_Card = c.ID
      and (used.FirstUse is null or used.FirstUse <= ca.BeginTime)
      and (used.LastUse is null or used.LastUse >= ca.BeginTime)
    order by
        case when used.FirstUse is null then 1 else 0 end,
        used.FirstUse desc,
        used.ID desc
) cvu
left join dbo.Vehicle v on v.ID = cvu.ID_Vehicle
left join dbo.VehicleIdentification vi on vi.ID = v.ID_VehicleIdentification
left join dbo.Nation vn on vn.ID = v.ID_Nation
where (:occurredFrom is null or ca.BeginTime >= :occurredFrom)
  and (:occurredTo is null or ca.BeginTime < :occurredTo)
  and (
      :lastSourcePackageId is null
      or coalesce(ca.ID_FileLog, cda.ID_FileLog, c.ID_FileLog, ca.ID) > try_convert(int, :lastSourcePackageId)
  )
/*
 * Organisation filtering can be added through Driver_I_90021 / Vehicle_I_90021
 * once the exact organisation subtree semantics are confirmed.
 */
