DROP TABLE IF EXISTS ropidgtfs_scheduled_trips_actual;
DROP TABLE IF EXISTS ropidgtfs_scheduled_trips;

CREATE TABLE IF NOT EXISTS ropidgtfs_scheduled_trips
AS
SELECT t0.*, now() as start_timestamp, now() as end_timestamp
FROM (
    SELECT
        t1.trip_id,
        t1.service_id,
        t1.run_number,
        t3.date,
        t7.route_id,
        t7.route_type,
        t7.route_short_name,
        t7.is_regional,
        t7.is_substitute_transport,
        t7.is_night,
        t8.trip_headsign,
        t8.trip_short_name,
        t8.block_id,
        t8.exceptional,
        LEAST(t5.arrival_time::INTERVAL, t5.departure_time::INTERVAL) AS min_stop_time,
        GREATEST(t6.arrival_time::INTERVAL, t6.departure_time::INTERVAL) AS max_stop_time
    FROM ropidgtfs_run_numbers t1
    LEFT JOIN ropidgtfs_services_first14days t3 ON t1.service_id = t3.service_id
    LEFT JOIN ropidgtfs_trips_minmaxsequences t4 ON t1.trip_id = t4.trip_id
    LEFT OUTER JOIN ropidgtfs_stop_times t5 ON t1.trip_id = t5.trip_id AND t5.stop_sequence = t4.min_stop_sequence
    LEFT OUTER JOIN ropidgtfs_stop_times t6 ON t1.trip_id = t6.trip_id AND t6.stop_sequence = t4.max_stop_sequence
    LEFT JOIN ropidgtfs_trips t8 ON t1.trip_id = t8.trip_id
    LEFT JOIN ropidgtfs_routes t7 ON t8.route_id = t7.route_id
) t0
WITH NO DATA;

CREATE TABLE IF NOT EXISTS ropidgtfs_scheduled_trips_actual (LIKE ropidgtfs_scheduled_trips);
CREATE INDEX ropidgtfs_departures_route_id_idx ON ropidgtfs_scheduled_trips_actual USING btree (route_id);
CREATE UNIQUE INDEX ropidgtfs_scheduled_trips_unique_id
    ON ropidgtfs_scheduled_trips_actual USING btree (trip_id, service_id, run_number, date, route_id);

ALTER TABLE ropidgtfs_scheduled_trips_actual INHERIT ropidgtfs_scheduled_trips;
