class Listing < ApplicationRecord
  has_many :bookings
  has_many :reservations

  def missions
    results = []
    bookings.each do |booking|
      # Reservation and Bookings could be cancelled, in this case
      # we should not do missions related.
      next if booking.cancelled?

      # We should have a cleaning mission called first_checkin
      # at the beginning of the booking
      results << {
        listing_id: self.id,
        mission_type: :first_checkin,
        date: booking.start_date,
        price: PRICES[:first_checkin],
      }

      # We should have a cleaning mission called last_checkout
      # before the owner comes back
      results << {
        listing_id: self.id,
        mission_type: :last_checkout,
        date: booking.end_date,
        price: PRICES[:last_checkout],
      }
    end

    reservations.each do |reservation|
      # Reservation and Bookings could be cancelled, in this case
      # we should not do missions related.
      next if reservation.cancelled?

      # We should have a cleaning mission called checkout_checkin
      # at the end of each reservation UNLESS there is already a
      # last_checkout at the same date
      next if results.detect { |result|
        result[:mission_type] == :last_checkout &&
        result[:date] == reservation.end_date
      }

      results << {
        listing_id: self.id,
        mission_type: :checkout_checkin,
        date: reservation.end_date,
        price: PRICES[:checkout_checkin],
      }
    end
    
    results
  end
end
