module JamRuby
  class TeacherPaymentCharge < Charge

    has_one :teacher_payment, class_name: "JamRuby::TeacherPayment", foreign_key: :charge_id

    def distribution
      @distribution ||= teacher_payment.teacher_distribution
    end

    def max_retries
      9999999
    end

    def teacher
      @teacher ||= teacher_payment.payable_teacher
    end

    def charged_user
      teacher
    end

    def actual_charge_in_cents
      amount_in_cents
    end
    def do_charge(force)

      metadata = {}

      begin
        metadata = {
            teacher_id: teacher.id,
            teacher_name: teacher.name,
            tax: 0,
        }
      rescue Exception => e
        metadata = {metaerror: true}
      end

      @stripe_charge = Stripe::Charge.create(
          :amount => actual_charge_in_cents,
          :currency => "usd",
          :customer => APP_CONFIG.stripe[:source_customer],
          :description => construct_description,
          :metadata => metadata,
          :destination => teacher.teacher.stripe_account_id
      )

      stripe_charge
    end

    def do_send_notices
      unless teacher_payment.school && distribution.is_monthly?
        # we don't send monthly success notices to the teacher if they are in a school, otherwise they get an email
        UserMailer.teacher_distribution_done(teacher_payment).deliver_now
      end
      if teacher_payment.school
        UserMailer.school_distribution_done(teacher_payment).deliver_now
      end
    end

    def do_send_unable_charge
      UserMailer.teacher_distribution_fail(teacher_payment).deliver_now
    end

    def construct_description
      teacher_payment.teacher_distribution.description
    end

  end
end