/*
 * VUGnssAccumulatedDriving POSITION extraction for the bytebar tachograph schema.
 */
with OrgTree as (
    select org.I_90021_OID
    from dbo.GetOrganisationTree(null, :organisationId, 0, null) org
    where :organisationId is not null
)
,
Base as (
    select
        pos.ID,
        pos.Timestamp as occurred_at,
        pos.Odo,
        pos.ID_FileLog,
        pos.ID_VUInstallation,
        coalesce(driverCard.ID, coDriverCard.ID) as card_id,
        coalesce(driverCard.ID_Driver, coDriverCard.ID_Driver) as driver_id,
        coalesce(driverNation.AlphaCode, coDriverNation.AlphaCode) as driver_card_nation,
        coalesce(driverCard.CardNumber, coDriverCard.CardNumber) as driver_card_number,
        gnss.Latitude as latitude,
        gnss.Longitude as longitude,
        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, pos.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, pos.Timestamp) as source_package_period_from,
        coalesce(fl.DownloadTo, pos.Timestamp) as source_package_period_to,
        coalesce(fl.CreationDate, fl.TStamp) as source_package_imported_at
    from dbo.VUGnssAccumulatedDriving pos
    join dbo.VUInstallation vui on vui.ID = pos.ID_VUInstallation
    join dbo.VehicleIdentification vi on vi.ID = vui.ID_VehicleIdentification
    left join dbo.Card driverCard on driverCard.ID = pos.ID_DriverCard
    left join dbo.Nation driverNation on driverNation.ID = driverCard.ID_Nation
    left join dbo.Card coDriverCard on coDriverCard.ID = pos.ID_CoDriverCard
    left join dbo.Nation coDriverNation on coDriverNation.ID = coDriverCard.ID_Nation
    join dbo.GnssPlace gnss on gnss.ID = pos.ID_GnssPlace
    left join dbo.FileLog fl on fl.ID = coalesce(pos.ID_FileLog, vui.ID_FileLog)
    where (:occurredFrom is null or pos.Timestamp >= :occurredFrom)
      and (:occurredTo is null or pos.Timestamp < :occurredTo)
)
,
Extracted as (
select
    cast(base.ID as varchar(128)) as source_row_id,
    concat('TACHOGRAPH:VU_POSITION:', base.ID) as external_source_event_id,

    base.occurred_at,
    base.received_partner_at,
    cast(base.Odo as bigint) * 1000 as odometer_m,
    base.latitude,
    base.longitude,

    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
          )
      )
)
