/*
 * CardVehiclesUsed DRIVER_CARD extraction for the bytebar tachograph schema.
 *
 * Each row is emitted as INSERT at FirstUse and WITHDRAW at LastUse when those
 * timestamps are available.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
CandidateUse as (
    select
        used.ID,
        used.ID_Card,
        used.ID_Vehicle,
        used.OdoBegin,
        used.OdoEnd,
        used.FirstUse,
        used.LastUse,
        used.ID_FileLog,
        used.VIN as used_vin,
        c.ID_Driver as driver_id,
        cn.AlphaCode as driver_card_nation,
        c.CardNumber as driver_card_number,
        v.ID_VehicleIdentification,
        vi.ID as vehicle_identification_id,
        coalesce(used.VIN, vi.VIN) as vehicle_vin,
        vn.AlphaCode as vehicle_registration_nation,
        v.VRN as vehicle_registration_number
    from dbo.CardVehiclesUsed used
    join dbo.Card c on c.ID = used.ID_Card
    left join dbo.Nation cn on cn.ID = c.ID_Nation
    left join dbo.Vehicle v on v.ID = used.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 (:occurredTo is null or used.FirstUse < :occurredTo or used.LastUse < :occurredTo)
      and (:occurredFrom is null or used.FirstUse >= :occurredFrom or used.LastUse >= :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
        used.ID,
        used.ID_Card,
        used.ID_Vehicle,
        used.driver_id,
        used.driver_card_nation,
        used.driver_card_number,
        used.vehicle_identification_id,
        used.vehicle_vin,
        used.vehicle_registration_nation,
        used.vehicle_registration_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, used.ID_FileLog) as source_package_id_raw,
        coalesce(fl.ID_Card, used.ID_Card) as source_package_entity_id_raw,
        coalesce(fl.DownloadFrom, used.FirstUse) as source_package_period_from,
        coalesce(fl.DownloadTo, used.LastUse, used.FirstUse) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at
    from CandidateUse used
    cross apply (values
        ('INSERT', used.FirstUse, cast(used.OdoBegin as bigint) * 1000),
        ('WITHDRAW', used.LastUse, cast(used.OdoEnd as bigint) * 1000)
    ) evt(lifecycle, occurred_at, odometer_m)
    left join dbo.FileLog fl on fl.ID = used.ID_FileLog
    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:CARD_VEHICLES_USED:', 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,
    cast(null as varchar(32)) 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(base.ID_Vehicle 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
)
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
          )
      )
)
