module JamRuby
  class LessonPaymentCharge < Charge

    has_one :lesson_session, class_name: "JamRuby::LessonSession", foreign_key: :charge_id
    has_one :lesson_package_purchase, class_name: "JamRuby::LessonPackagePurchase", foreign_key: :charge_id

    def max_retries
      5
    end

    def charged_user
      user
    end

    def resolve_target
      if is_lesson?
        lesson_session
      else
        lesson_package_purchase
      end
    end
    def target
      @target ||= resolve_target
    end

    def lesson_booking
      @lesson_booking ||= target.lesson_booking
    end

    def student
      charged_user
    end

    def teacher
      target.teacher
    end

    def is_lesson?
      !lesson_session.nil?
    end


    # stupid way to inject a failure
    def post_sale_test_failure
      return true
    end

    def do_charge(force)

      if is_lesson?
        result = Sale.purchase_lesson(self, student, lesson_booking, lesson_booking.lesson_package_type, lesson_session)
      else
        result = Sale.purchase_lesson(self, student, lesson_booking, lesson_booking.lesson_package_type, nil, lesson_package_purchase, force)
        lesson_booking.unsuspend! if lesson_booking.is_suspended?
      end

      stripe_charge = result[:stripe_charge]

      self.amount_in_cents = stripe_charge.amount
      self.save(validate: false)

      # update teacher distribution, because it's now ready to be given to them!

      post_sale_test_failure

      target.teacher_distributions.update_all(ready:true) # possibly there are 0 distributions on this lesson


      stripe_charge
    end

    def do_send_notices
      if is_lesson?
        UserMailer.student_lesson_normal_done(lesson_session).deliver_now
        UserMailer.teacher_lesson_normal_done(lesson_session).deliver_now
      else
        UserMailer.student_lesson_monthly_charged(lesson_package_purchase).deliver_now
        UserMailer.teacher_lesson_monthly_charged(lesson_package_purchase).deliver_now
      end
    end

    def do_send_unable_charge
      if is_lesson?
        UserMailer.student_unable_charge(lesson_session)
      else
        if !billing_should_retry
          lesson_booking.suspend!
        end

        UserMailer.student_unable_charge_monthly(lesson_package_purchase)
        if lesson_booking.is_suspended?
          # let the teacher know that we are having problems collecting from the student
          UserMailer.teacher_unable_charge_monthly(lesson_package_purchase)
        end
      end
    end

    def description
      target.timed_description
    end

    def expected_price_in_cents
      distribution = target.teacher_distribution
      for_education = distribution && distribution.education
      target.lesson_booking.distribution_price_in_cents(target, for_education)
    end
  end
end