-- name: GetStationsByName :many
SELECT s.id,
       s.name,
       sl.latitude,
       sl.longitude,
       bus,
       taxi,
       tram,
       ferry,
       subway,
       national,
       regional,
       suburban,
       regionalexp,
       nationalexp
FROM stops s
    JOIN public.stat_locations sl
        on sl.id = s.location_id
    JOIN public.stat_services ss
        on ss.id = s.service_id
WHERE s.id
          in (SELECT id
              FROM stops s2
              WHERE s2.name LIKE $1
              );

-- name: GetStationById :one
SELECT s.id,
       s.name,
       sl.latitude,
       sl.longitude,
       bus,
       taxi,
       tram,
       ferry,
       subway,
       national,
       regional,
       suburban,
       regionalexp,
       nationalexp
FROM stops s
         JOIN public.stat_locations sl
              on sl.id = s.location_id
         JOIN public.stat_services ss
              on ss.id = s.service_id
WHERE s.id = $1;

-- name: GetDeparturesById :many
SELECT DISTINCT (t.id) as "id",
                t.line_name as "lineName",
                t.line_productname as "lineProductName",
                so.departuredelay as "departureDelay",
                sd.id as "directionId",
                sd.name as "directionName",
                so.departure as "departure",
                so.planneddeparture as "plannedDeparture",
                so.departureplatform as "departurePlattform",
                so.planneddepartureplatform as "plannedDeparturePlattform",
                so.realtimedataupdatedat as "realtimeDataUpdatedAt"
FROM stopovers so
         JOIN trips t ON so.id = t.id
         JOIN public.trip_meta tm on t.id = tm.id
         JOIN public.stops sd on t.destination = sd.id
WHERE so.stop = $1
  AND (so.id, so.realtimedataupdatedat) IN (SELECT DISTINCT (id), max(realtimedataupdatedat)
                                            FROM stopovers so2
                                            WHERE so2.stop = $1
                                              AND (so2.departure > $2)
                                              AND (so2.departure < $3)
                                              AND (so2.realtimedataupdatedat <= $4)
                                            GROUP BY so2.id
                                            LIMIT 50)
ORDER BY so.departure ASC;
