class Family::Legacy::LunchesController < Family::Controller
  include DateRangeHelper

  def index
    render_success :ok, json: family_student_orders(params[:date]).map { |o| lunch_props(o) }
  end

  def count
    render_success :ok, json: family_student_order_count
  end

  def week_count
    render_success :ok, json: mapped_lunch_dates
  end

  def create
    return render_error :unprocessable_entity if lunch_cycle.nil?

    orders = []
    params[:orders].each do |order|
      student = current_students[order[:student_id]]
      student_order = current_family.student_lunch_orders.find_or_initialize_by(
        school_year: current_school_year,
        student_id: student.id,
        lunch_day: lunch_day
      )
      student_order.lunch_price_plan_id = student&.lunch_price_plan&.id || 0
      student_order.assign_attributes(order_params(order))
      orders << student_order
    end

    if transactional_save(orders)
      render_success :ok, message: 'Orders created successfully'
    else
      render_error :unprocessable_entity, errors: multi_errors(orders)
    end
  end

  private
    def family_student_orders(date)
      @family_student_orders ||= current_user.family.student_lunch_orders
        .joins(:lunch_day)
        .by_lunch_date(date)
    end

    def family_student_order_count
      family_student_orders(Time.zone.today)
        .group_by(&:meal_id)
        .map do |meal_id, orders|
          { meal_id: meal_id, count: orders.sum(&:quantity) }
        end
    end

    def lunch_cycle
      @lunch_cycle ||= current_school.lunch_cycles
        .by_open(true)
        .find_by('? BETWEEN StartDate AND EndDate', params[:date])
    end

    def lunch_day
      @lunch_day ||= current_school_year.lunch_days.find_by(date: params[:date])
    end

    def current_students
      @current_students ||= current_family.students.index_by(&:id)
    end

    def mapped_lunch_dates
      family_student_orders(date_range(params[:dates]))
        .group_by(&:lunch_day_id)
        .map { |id, orders| { id: id, orders: orders_by_meal(orders) } }
    end

    def orders_by_meal(orders)
      orders
        .group_by(&:meal_id)
        .map do |meal_id, items|
          { meal_id: meal_id, count: items.sum(&:quantity) }
        end
    end

    def order_params(param)
      param.permit(:quantity, :meal_id).merge(lunch_cycle: lunch_cycle, order_date: Date.current)
    end

    def lunch_props(order)
      {
        id: order.id,
        student_id: order.student_id,
        meal_id: order.meal_id,
        quantity: order.quantity,
        charged: order.charge_date.present?
      }
    end
end
