class Csv::Tep::SchoolService < Csv::ApplicationService
  def initialize(school)
    @school = school
  end

  def call
    CSV.generate do |csv|
      csv << headers
      students.each do |student|
        student.family.primary_contacts.each do |contact|
          next if contact.email.nil?

          csv << content(student, contact)
        end
      end
    end
  end

  private
    def students
      @students ||= @school.students
        .preload(family: :primary_contacts)
        .join_school_year_student(@school.current_year.id, :current)
    end

    def grade_levels
      @grade_levels ||= @school.grades_hash
    end

    def headers
      [
        'Student ID',
        'Student First Name',
        'Student Last Name',
        'Group',
        'Grade',
        'Fee',
        'Fee Type',
        'Fee Amount',
        'Payment Cycle',
        'Interval',
        'Due Date',
        'Parent External Id',
        'Parent First Name',
        'Parent Last Name',
        'Parent Email',
        'Address',
        'City',
        'State',
        'Zip',
        'Phone',
        'Guarantor is Student',
        'Surplus',
        'Balance Due',
        'Financial Aid'
      ]
    end

    def content(student, contact)
      [
        student.id,
        student.first_name,
        student.last_name,
        nil,
        grade_levels[student.grade],
        nil,
        nil,
        nil,
        nil,
        nil,
        nil,
        contact.id,
        contact.first_name,
        contact.last_name,
        contact.email,
        "#{student.family.address} #{student.family.address_2}".strip,
        student.family.city.presence,
        student.family.state.presence,
        student.family.zip.presence,
        contact.cell_phone.presence,
        false,
        nil,
        nil,
        false
      ]
    end
end
