/*
 * IWCycle DRIVER_CARD extraction for the bytebar tachograph schema.
 *
 * Each IWCycle row describes a card inserted into a vehicle unit. It is emitted
 * as two point events when timestamps are available: INSERT at BeginTime and
 * WITHDRAW at EndTime.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
CandidateCycle as (
    select
        iw.ID,
        iw.BeginTime,
        iw.EndTime,
        iw.OdoBegin,
        iw.OdoEnd,
        iw.Slot,
        iw.ID_FileLog,
        iw.ID_Card,
        iw.ID_VUInstallation,
        vui.ID_VehicleIdentification,
        vui.ID_FileLog as vui_filelog_id,
        vi.ID as vehicle_identification_id,
        vi.VIN as vehicle_vin,
        c.ID_Driver as driver_id,
        cn.AlphaCode as driver_card_nation,
        c.CardNumber as driver_card_number,
        coalesce(iw.ID_FileLog, vui.ID_FileLog) as file_log_id
    from dbo.IWCycle iw
    join dbo.VUInstallation vui on vui.ID = iw.ID_VUInstallation
    join dbo.VehicleIdentification vi on vi.ID = vui.ID_VehicleIdentification
    left join dbo.Card c on c.ID = iw.ID_Card
    left join dbo.Nation cn on cn.ID = c.ID_Nation
    where (:occurredTo is null or iw.BeginTime < :occurredTo or iw.EndTime < :occurredTo)
      and (:occurredFrom is null or iw.BeginTime >= :occurredFrom or iw.EndTime >= :occurredFrom)
)
,
Base as (
    select
        cycle.ID,
        cycle.Slot,
        cycle.ID_FileLog,
        cycle.vui_filelog_id,
        cycle.ID_Card,
        cycle.ID_VUInstallation,
        cycle.vehicle_identification_id,
        cycle.vehicle_vin,
        cycle.driver_id,
        cycle.driver_card_nation,
        cycle.driver_card_number,
        evt.lifecycle,
        evt.occurred_at,
        evt.odometer_m,
        coalesce(fl.DownloadDate, fl.OriginalDownloadDate, fl.TStamp, fl.CreationDate) as received_partner_at,
        coalesce(fl.ID, cycle.ID_FileLog, cycle.vui_filelog_id) as source_package_id_raw,
        coalesce(fl.ID_VehicleIdentification, cycle.ID_VehicleIdentification) as source_package_entity_id_raw,
        coalesce(fl.DownloadFrom, cycle.BeginTime) as source_package_period_from,
        coalesce(fl.DownloadTo, cycle.EndTime, cycle.BeginTime) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at
    from CandidateCycle cycle
    cross apply (values
        ('INSERT', cycle.BeginTime, cast(cycle.OdoBegin as bigint) * 1000),
        ('WITHDRAW', cycle.EndTime, cast(cycle.OdoEnd as bigint) * 1000)
    ) evt(lifecycle, occurred_at, odometer_m)
    left join dbo.FileLog fl on fl.ID = cycle.file_log_id
    where evt.occurred_at is not null
      and (:occurredFrom is null or evt.occurred_at >= :occurredFrom)
      and (:occurredTo is null or evt.occurred_at < :occurredTo)
)
,
Extracted as (
select
    cast(base.ID as varchar(128)) as source_row_id,
    concat('TACHOGRAPH:IW_CYCLE:', base.ID, ':', base.lifecycle) as external_source_event_id,

    base.occurred_at,
    base.received_partner_at,
    case base.lifecycle
        when 'INSERT' then 'CARD_INSERTED'
        when 'WITHDRAW' then 'CARD_WITHDRAWN'
        else 'UNKNOWN_EVENT'
    end as event_type,
    base.lifecycle,
    base.Slot as card_slot,
    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(v.ID as varchar(128)) as vehicle_registration_source_entity_id,
    vn.AlphaCode as vehicle_registration_nation,
    v.VRN as 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
outer apply (
    select top 1 vehicle.ID,
                 vehicle.VRN,
                 vehicle.ID_Nation
    from dbo.Vehicle vehicle
    where vehicle.ID_VehicleIdentification = base.vehicle_identification_id
      and (vehicle.ValidFrom is null or vehicle.ValidFrom <= base.occurred_at)
      and (vehicle.ValidTo is null or vehicle.ValidTo > base.occurred_at)
    order by
        vehicle.ValidFrom desc,
        vehicle.ID desc
) v
left join dbo.Nation vn on vn.ID = v.ID_Nation
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
      )
  )
)
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
          )
      )
)
