/*
 * SpeedingEvents SPEEDING extraction for the bytebar tachograph schema.
 *
 * The source row is an interval. The normalized event contract is point-based,
 * so this query emits a BEGIN point at BeginTime and an END point at EndTime.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
Base as (
    select
        speeding.ID,
        speeding.BeginTime,
        speeding.EndTime,
        speeding.AvgSpeed,
        speeding.MaxSpeed,
        speeding.ID_FileLog,
        speeding.ID_VUInstallation,
        c.ID as card_id,
        c.ID_Driver as driver_id,
        cn.AlphaCode as driver_card_nation,
        c.CardNumber as driver_card_number,
        vui.ID_FileLog as vui_filelog_id,
        vui.ID_VehicleIdentification,
        vi.ID as vehicle_identification_id,
        vi.VIN as vehicle_vin,
        coalesce(fl.DownloadDate, fl.OriginalDownloadDate, fl.TStamp, fl.CreationDate) as received_partner_at,
        coalesce(fl.ID, speeding.ID_FileLog, vui.ID_FileLog) as source_package_id_raw,
        coalesce(fl.ID_VehicleIdentification, vui.ID_VehicleIdentification) as source_package_entity_id_raw,
        coalesce(fl.DownloadFrom, speeding.BeginTime) as source_package_period_from,
        coalesce(fl.DownloadTo, speeding.EndTime, speeding.BeginTime) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at
    from dbo.SpeedingEvents speeding
    join dbo.VUInstallation vui on vui.ID = speeding.ID_VUInstallation
    join dbo.VehicleIdentification vi on vi.ID = vui.ID_VehicleIdentification
    left join dbo.Card c on c.ID = speeding.ID_Card
    left join dbo.Nation cn on cn.ID = c.ID_Nation
    left join dbo.FileLog fl on fl.ID = coalesce(speeding.ID_FileLog, vui.ID_FileLog)
    where (
          :occurredFrom is null
          or speeding.BeginTime >= :occurredFrom
          or speeding.EndTime >= :occurredFrom
      )
      and (
          :occurredTo is null
          or speeding.BeginTime < :occurredTo
          or speeding.EndTime < :occurredTo
      )
)
,
Events as (
    select
        base.*,
        base.BeginTime as occurred_at,
        'BEGIN' as lifecycle
    from Base base
    union all
    select
        base.*,
        base.EndTime as occurred_at,
        'END' as lifecycle
    from Base base
)
,
Extracted as (
select
    concat(cast(events.ID as varchar(128)), ':', events.lifecycle) as source_row_id,
    concat('TACHOGRAPH:SPEEDING_EVENTS:', events.ID, ':', events.lifecycle) as external_source_event_id,

    events.occurred_at,
    events.received_partner_at,
    cast(events.AvgSpeed as decimal(10, 2)) as avg_speed_kmh,
    cast(events.MaxSpeed as decimal(10, 2)) as max_speed_kmh,
    events.lifecycle,

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

    cast(events.vehicle_identification_id as varchar(128)) as vehicle_source_entity_id,
    events.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(events.source_package_id_raw as varchar(128)) as source_package_id,
    events.source_package_id_raw as source_package_sort_id,
    cast(events.source_package_entity_id_raw as varchar(128)) as source_package_entity_id,
    events.source_package_period_from,
    events.source_package_period_to,
    events.source_package_imported_at
from Events events
outer apply (
    select top 1 vehicle.ID,
                 vehicle.VRN,
                 vehicle.ID_Nation
    from dbo.Vehicle vehicle
    where vehicle.ID_VehicleIdentification = events.vehicle_identification_id
      and (vehicle.ValidFrom is null or vehicle.ValidFrom <= events.occurred_at)
      and (vehicle.ValidTo is null or vehicle.ValidTo > events.occurred_at)
    order by
        vehicle.ValidFrom desc,
        vehicle.ID desc
) v
left join dbo.Nation vn on vn.ID = v.ID_Nation
where (:occurredFrom is null or events.occurred_at >= :occurredFrom)
  and (:occurredTo is null or events.occurred_at < :occurredTo)
  and (
      :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
          )
      )
)
