class Family::Legacy::AlaCarteController < Family::Controller
  def index
    render_success :ok, json: family_student_items(params[:date]).map { |i| ala_carte_props(i) }
  end

  def create
    orders = []
    params[:orders].each do |order|
      student_order = current_family.student_item_orders.find_or_initialize_by(
        item_id: order[:item_id],
        school_year: current_school_year,
        student_id: order[: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, json: orders.map { |o| ala_carte_props(o) }
    else
      render_error :unprocessable_entity, errors: multi_errors(orders)
    end
  end

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

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

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

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

    def ala_carte_props(item)
      {
        id: item.id,
        student_id: item.student_id,
        item_id: item.item_id,
        quantity: item.quantity,
        charged: item.charge_date.present?
      }
    end
end
