create schema SignificantDrivingInterval(
    sessionId java.util.UUID,
    driverKey string,
    firstSourceIntervalId string,
    lastSourceIntervalId string,
    startedAtEpochSecond long,
    endedAtEpochSecond long,
    durationSeconds long,
    registrationKey string,
    vehicleKey string
);

create schema DrivingInterruptionInterval(
    sessionId java.util.UUID,
    driverKey string,
    startedAtEpochSecond long,
    endedAtEpochSecond long,
    durationSeconds long,
    previousDrivingSourceIntervalId string,
    nextDrivingSourceIntervalId string,
    previousRegistrationKey string,
    nextRegistrationKey string,
    previousVehicleKey string,
    nextVehicleKey string
);

insert into SignificantDrivingInterval
select
    sessionId,
    driverKey,
    firstSourceIntervalId,
    lastSourceIntervalId,
    startedAtEpochSecond,
    endedAtEpochSecond,
    durationSeconds,
    registrationKey,
    vehicleKey
from TachographActivityIntervalInputEvent(activityType = 'DRIVE', durationSeconds > ${SIGNIFICANT_DRIVING_THRESHOLD_SECONDS});

create window PreviousSignificantDrivingInterval#unique(driverKey) as SignificantDrivingInterval;

on SignificantDrivingInterval as next
insert into DrivingInterruptionInterval
select
    priorInterval.sessionId as sessionId,
    priorInterval.driverKey as driverKey,
    priorInterval.endedAtEpochSecond as startedAtEpochSecond,
    next.startedAtEpochSecond as endedAtEpochSecond,
    next.startedAtEpochSecond - priorInterval.endedAtEpochSecond as durationSeconds,
    priorInterval.lastSourceIntervalId as previousDrivingSourceIntervalId,
    next.firstSourceIntervalId as nextDrivingSourceIntervalId,
    priorInterval.registrationKey as previousRegistrationKey,
    next.registrationKey as nextRegistrationKey,
    priorInterval.vehicleKey as previousVehicleKey,
    next.vehicleKey as nextVehicleKey
from PreviousSignificantDrivingInterval as priorInterval
where priorInterval.driverKey = next.driverKey
  and next.startedAtEpochSecond > priorInterval.endedAtEpochSecond;

@Priority(20)
on SignificantDrivingInterval
delete from PreviousSignificantDrivingInterval;

@Priority(10)
on SignificantDrivingInterval as current
insert into PreviousSignificantDrivingInterval
select *;

@name('drivingInterruptionIntervals')
select * from DrivingInterruptionInterval;
