class Family::Legacy::LunchCyclesController < Family::Controller
  def index
    render_success :ok, json: lunch_cycles.map { |c| lunch_cycle_props(c) }
  end

  def open_dates
    days = []
    lunch_days.map { |day| days << lunch_day_props(day) } if active_cycles.present?

    render_success :ok, json: days
  end

  private
    def active_cycles
      @active_cycles ||= current_school.lunch_cycles
        .by_start_and_end_dates
        .by_open_or_ala_carte(true)
        .by_active(tomorrow)
        .order(:end_date)
    end

    def earliest_active_cycle
      @earliest_active_cycle ||= active_cycles.min_by(&:start_date)
    end

    def lunch_days
      @lunch_days ||= current_school_year.lunch_days
        .has_meals_or_ala_carte
        .by_date(start_date..active_cycles.last.end_date)
        .order(:date)
    end

    def start_date
      @start_date ||= if earliest_active_cycle.start_date > tomorrow
        earliest_active_cycle.start_date
      else
        tomorrow
      end
    end

    def tomorrow
      @tomorrow ||= Date.current + 1.day
    end

    def lunch_cycle_props(cycle)
      {
        id: cycle.id,
        name: cycle.name,
        start_date: cycle.start_date,
        end_date: cycle.end_date
      }
    end

    def lunch_day_props(day)
      # since lunch cycles and days are not related we can't check which day belongs to a cycle
      # we have to instead find the day by the date and manually check each active cycle to see
      # if it contains the day (they can overlap).

      cycles_for_day = []
      active_cycles.each do |cycle|
        cycles_for_day << cycle if cycle.start_date <= day.date && cycle.end_date >= day.date
      end
      ala_carte_cycle = cycles_for_day.find(&:ala_carte?)
      open_cycle = cycles_for_day.find(&:open?)
      {
        date: day.date,
        ala_carte: ala_carte_cycle.present? && day.ala_carte?,
        open: open_cycle.present?
      }
    end
end
