class Csv::Admissions::Applicants::PaymentService < Csv::Admissions::Applicants::Service
  def initialize(school, options)
    @school = school
    @school_year_id = options['school_year_id']
    @application_id = options['application_id']
    @payment_status = options['payment_status']
    @grade = options['grades']
    @system_status = options['status']
    @returning = options['student_type']
    @enrollment = options['enrollment']
    @review = options['review']
    @tags = options['tags']
  end

  def call
    CSV.generate do |csv|
      csv << headers
      applicants.each do |applicant|
        csv << content(applicant)
      end
    end
  end

  private
    def applicants
      @applicants ||= school_year.admission_applicants
        .includes(:tags, :family, :student, :application)
        .where(admission_applications: { enrollment: @enrollment })
        .with_application(@application_id)
        .by_application_payment(@payment_status.present?)
        .by_payment_status(@payment_status)
        .with_grade(@grade)
        .with_system_status(@system_status)
        .with_returning(@returning)
        .by_review(@review)
        .with_tags(@tags)
        .ordered
        .decorate
        .to_a
    end

    def headers
      [
        'Student ID',
        'Student Code',
        'Student Name',
        'Application Name',
        'Application Grade Code',
        'Application Grade Label',
        'Family Code',
        'Family Name',
        'Application Fee Description',
        'Application Fee Amount',
        'Paid Status',
        'Paid Date',
        'Applicant Tags',
        'Family Tags'
      ]
    end

    def content(applicant)
      [
        applicant.student&.id,
        applicant.student&.code,
        applicant.reviewed_prop(:full_name),
        applicant.application.name,
        applicant.grade,
        grade_levels[applicant.grade],
        applicant.family.code,
        applicant.family.name,
        applicant.payment_description,
        applicant.payment_amount,
        applicant.payment_status&.titleize || 'Not paid',
        applicant.paid_at,
        applicant.tags.map(&:name).join(', '),
        family_tags[applicant.family_id]&.tags&.map(&:name)&.join(', ')
      ]
    end
end
