class Admission::Config < ApplicationRecord
  include Castable

  audited

  cast_as_editor_content :welcome_message

  attr_accessor :skip_callback

  belongs_to :school
  belongs_to :school_year, optional: true

  validate :payment_processor_configured, if: :online_payment

  before_validation :validate_portal_and_regisration

  before_save :mark_payment_options

  after_save :update_family_access, unless: :skip_callback

  private
    def payment_processor_configured
      return if school.stripe_connect_account&.stripe_account_id.present?
      return if school.find_or_build_paya_config.enabled?
      return if school.find_or_build_payjunction_config.enabled?

      errors.add(:payment_processor, 'must be configured')
    end

    def validate_portal_and_regisration
      self.portal = true if registration_changed? && !portal_changed? && registration?
      self.registration = false unless portal?
    end

    def update_family_access
      return unless saved_change_to_portal?

      school.find_or_build_family_module.update(admissions: portal, skip_callback: true)
    end

    def mark_payment_options
      if payment == false
        self.family_payment = false
        self.online_payment = false
        self.applicant_payment = false
      end

      return if applicant_payment?

      school.admission_applications.update_all(payment: false)
    end
end
