/*
 * 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.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
CandidateActivity as (
    select
        ca.ID,
        ca.BeginTime,
        activity_time.EndTime,
        ca.Activity,
        ca.Slot,
        ca.CardStatus,
        ca.DrivingStatus,
        ca.ID_FileLog,
        cda.RecordDate,
        cda.RecordDateTo,
        cda.ID_FileLog as cda_filelog_id,
        c.ID as card_id,
        c.ID_Driver as driver_id,
        c.ID_Nation as driver_card_nation_id,
        c.CardNumber as driver_card_number,
        c.ID_FileLog as card_filelog_id,
        coalesce(ca.ID_FileLog, cda.ID_FileLog, c.ID_FileLog) as file_log_id
    from dbo.CardActivity ca
    join dbo.CardDailyActivity cda on cda.ID = ca.ID_DailyActivity
    join dbo.Card c on c.ID = cda.ID_Card
    cross apply (values (dateadd(minute, coalesce(ca.Duration, 0), ca.BeginTime))) activity_time(EndTime)
    where (:occurredTo is null or ca.BeginTime < :occurredTo)
      and (
          :occurredFrom is null
          or ca.BeginTime >= :occurredFrom
          or activity_time.EndTime >= :occurredFrom
      )
      and (
          :organisationId is null
          or exists (
              select 1
              from dbo.Driver_I_90021 rel
              join OrgTree on OrgTree.I_90021_OID = rel.ID_I_90021
              where rel.ID_Driver = c.ID_Driver
                and rel.GILT_BIS is null
          )
      )
)
,
Base as (
    select
        ca.ID,
        ca.BeginTime,
        ca.EndTime,
        ca.Activity,
        ca.Slot,
        ca.CardStatus,
        ca.DrivingStatus,
        ca.ID_FileLog,
        ca.cda_filelog_id,
        ca.card_filelog_id,

        coalesce(fl.DownloadDate, fl.OriginalDownloadDate, fl.TStamp, fl.CreationDate) as received_partner_at,
        coalesce(fl.ID, ca.ID_FileLog, ca.cda_filelog_id, ca.card_filelog_id) as source_package_id_raw,
        coalesce(fl.ID_Card, ca.card_id) as source_package_entity_id_raw,
        coalesce(fl.DownloadFrom, ca.RecordDate) as source_package_period_from,
        coalesce(fl.DownloadTo, ca.RecordDateTo, dateadd(day, 1, ca.RecordDate)) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at,

        ca.driver_id,
        cn.AlphaCode as driver_card_nation,
        ca.driver_card_number,
        coalesce(cvu.ID_Vehicle, v.ID) as vehicle_registration_id,
        null as vehicle_vin,
        vn.AlphaCode as vehicle_registration_nation,
        v.VRN as vehicle_registration_number
    from CandidateActivity ca
    left join dbo.FileLog fl on fl.ID = ca.file_log_id
    left join dbo.Nation cn on cn.ID = ca.driver_card_nation_id
    outer apply (
        select top 1 used.ID_Vehicle
        from dbo.CardVehiclesUsed used
        where used.ID_Card = ca.card_id
          and (used.FirstUse is null or used.FirstUse <= ca.BeginTime)
          and (used.LastUse is null or used.LastUse >= ca.BeginTime)
        order by
            used.FirstUse desc,
            used.ID desc
    ) cvu
    left join dbo.Vehicle v on v.ID = cvu.ID_Vehicle
    left join dbo.Nation vn on vn.ID = v.ID_Nation
)
,
Extracted as (
select
    cast(base.ID as varchar(128)) as source_row_id,
    concat('TACHOGRAPH:CARD_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,
    cast(null as bigint) as odometer_m,

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

    cast(null 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,

    'DRIVER_CARD' 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: driver 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
          )
      )
)
