class StudentLunchOrder < Base::StudentLunchOrder
  # order_date is used by milk orders the same way as lunch day is for lunch orders
  attr_accessor :milk_quantity, :milk_order_date

  associations_for legacy: true do |a|
    a.belongs_to :classroom, keys: :ClassID, optional: true
    a.belongs_to :family
    a.belongs_to :lunch_day
    a.belongs_to :lunch_cycle, optional: true
    a.belongs_to :meal, keys: :MealID, class_name: 'LunchMeal', optional: true
    a.belongs_to :school
    a.belongs_to :school_year
    a.belongs_to :student
    a.belongs_to :cafeteria_transaction, keys: :LTID, class_name: 'StudentCafeteriaTransaction',
      inverse_of: :lunch_order, optional: true
    a.belongs_to :lunch_price_plan, keys: :LPPID, optional: true
  end

  validates :quantity, numericality: { greater_than_or_equal_to: 0 }

  validate :changes_to_charged_order, if: :charge_date?

  after_initialize :set_association_defaults

  before_save :set_meal_and_quantity_defaults
  before_save :create_or_update_milk_orders, if: :milk_quantity

  after_save :destroy_zero_quantity

  scope :by_order_date, ->(date) { where(order_date: date) if date }
  scope :by_lunch_date, ->(date) { merge(LunchDay.by_date(date)) }

  private
    def set_association_defaults
      self.school = student.school if school_id.zero?
      self.family = student.family if family_id.zero?
    end

    def set_meal_and_quantity_defaults
      self.meal_id = 0 if meal_id.nil?
      self.quantity = 0 if quantity.nil?
    end

    def changes_to_charged_order
      return unless quantity_changed? || meal_id_changed?

      errors.add(:base, 'Cannot change a charged order')
    end

    def create_or_update_milk_orders
      milk_order = student.student_milk_orders.find_or_initialize_by(order_date: milk_order_date)
      milk_order.update!(quantity: milk_quantity.to_i, classroom: classroom)
    end

    def destroy_zero_quantity
      destroy! if quantity.zero? || meal.nil?
    end
end
