optimize this code 
# # # # app/controllers/api/v1/schedules_controller.rb
# # # class Api::V1::SchedulesController < ApplicationController
# # #   def index
# # #     departure_station = params[:departure]
# # #     destination_station = params[:destination]

# # #     if departure_station.present? && destination_station.present?
# # #       schedules = Schedule.joins(stations: { schedule: { route: :bus_schedule } })
# # #                           .where(stations: { name: departure_station })
# # #                           .where(id: Schedule.joins(stations: { schedule: { route: :bus_schedule } })
# # #                                               .where(stations: { name: destination_station })
# # #                                               .pluck(:id))
# # #                           .group(:trip)
# # #                           .order(:trip)

# # #       render json: schedules.map { |schedule|
# # #         {
# # #           trip: schedule.trip,
# # #           stations: schedule.stations.map { |station|
# # #             {
# # #               station: station.name,
# # #               arrivalTime: station.arrival_time,
# # #               departureTime: station.departure_time
# # #             }
# # #           }
# # #         }
# # #       }, status: :ok
# # #     else
# # #       render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
# # #     end
# # #   end
# # # end
# # # app/controllers/api/v1/schedules_controller.rb
# # class Api::V1::SchedulesController < ApplicationController
# #   def index
# #     departure_station = params[:departure]
# #     destination_station = params[:destination]

# #     if departure_station.present? && destination_station.present?
# #       # First, find schedules that start with the departure station
# #       departing_schedules = Schedule.joins(stations: { schedule: { route: :bus_schedule } })
# #                                     .where(stations: { name: departure_station })

# #       # Next, find the schedules that end with the destination station
# #       arriving_schedules = Schedule.joins(stations: { schedule: { route: :bus_schedule } })
# #                                    .where(stations: { name: destination_station })

# #       # Select only schedules which are common in both departing_schedules and arriving_schedules
# #       # and where the departure station comes before the destination station in sequence
# #       valid_schedules = departing_schedules.where(id: arriving_schedules.pluck(:id))
# #                                            .includes(:stations)
# #                                            .select { |schedule|
# #                                              dep_index = schedule.stations.index { |s| s.name == departure_station }
# #                                              dest_index = schedule.stations.index { |s| s.name == destination_station }
# #                                              dep_index.present? && dest_index.present? && dep_index < dest_index
# #                                            }
# #       # Now format the valid_schedules as needed
# #       render json: valid_schedules.map { |schedule|
# #         {
# #           vehicle_number: schedule.route.bus_schedule.vehicle_number,
# #           trip: schedule.trip,
# #           stations: schedule.stations.map { |station|
# #             {
# #               station: station.name,
# #               arrivalTime: station.arrival_time,
# #               departureTime: station.departure_time
# #             }
# #           }
# #         }
# #       }, status: :ok
# #     else
# #       render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
# #     end
# #   end
# # end
# class Api::V1::SchedulesController < ApplicationController
#   def index
#     departure_station = params[:departure]
#     destination_station = params[:destination]

#     if departure_station.present? && destination_station.present?
#       # Assuming here Schedule has a relation route which in turn has bus_schedule
#       valid_schedules = Schedule.joins(route: :bus_schedule)
#                                 .joins(:stations)
#                                 .where(stations: { name: [departure_station, destination_station] })
#                                 .distinct
#                                 .select('schedules.*, bus_schedules.vehicle_number')
#                                 .group_by { |schedule| schedule.route.bus_schedule.vehicle_number }

#       render json: valid_schedules.map { |vehicle_number, schedules|
#         {
#           vehicle_number: vehicle_number,
#           trips: schedules.select { |schedule|
#             dep_index = schedule.stations.index { |s| s.name == departure_station }
#             dest_index = schedule.stations.index { |s| s.name == destination_station }
#             dep_index.present? && dest_index.present? && dep_index < dest_index
#           }.map { |schedule|
#             {
#               trip: schedule.trip,
#               stations: schedule.stations.map { |station|
#                 {
#                   station: station.name,
#                   arrivalTime: station.arrival_time,
#                   departureTime: station.departure_time
#                 }
#               }
#             }
#           }
#         }
#       }, status: :ok
#     else
#       render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
#     end
#   end
# end
class Api::V1::SchedulesController < ApplicationController
  def index
    departure_station = params[:departure]
    destination_station = params[:destination]

    if departure_station.present? && destination_station.present?
      valid_schedules = Schedule.joins(route: :bus_schedule)
                                .joins(:stations)
                                .where(stations: { name: [departure_station, destination_station] })
                                .distinct
                                .group_by { |schedule| schedule.route.bus_schedule.vehicle_number }

      vehicle_trips = valid_schedules.each_with_object({}) do |(vehicle_number, schedules), acc|
        trips = schedules.select do |schedule|
          dep_index = schedule.stations.index { |s| s.name == departure_station }
          dest_index = schedule.stations.index { |s| s.name == destination_station }
          dep_index.present? && dest_index.present? && dep_index < dest_index
        end.map do |schedule|
          {
            trip: schedule.trip,
            stations: schedule.stations.map { |station|
              { 
                station: station.name,
                arrivalTime: station.arrival_time,
                departureTime: station.departure_time
              }
            }
          }
        end

        # Only include vehicles that have at least one valid trip.
        acc[vehicle_number] = trips if trips.any?
      end

      render json: vehicle_trips.map { |vehicle_number, trips|
        {
          vehicle_number: vehicle_number,
          trips: trips
        }
      }, status: :ok
    else
      render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
    end
  end
end

here is the relations
# app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord
  has_many :routes
end

# app/models/route.rb
class Route < ApplicationRecord
  belongs_to :bus_schedule
  has_many :schedules
end

# app/models/schedule.rb
class Schedule < ApplicationRecord
  belongs_to :route
  has_many :stations
end

# app/models/station.rb
class Station < ApplicationRecord
  belongs_to :schedule
end