class Csv::Admissions::Applicants::AgreementService < Csv::Admissions::Applicants::Service
  private
    def agreements
      @agreements ||= @school.admission_agreements
        .joins(:applications)
        .where(admission_applications: { id: applicants.map(&:application_id) })
        .pluck(:id, :name)
        .to_h
    end

    def associations
      [:family, :applicant_agreements, :tags]
    end

    def headers
      defaults = [
        'Student Code',
        'Student ID',
        'Student First Name',
        'Student Last Name',
        'Student Application Grade Code',
        'Student Application Grade Label',
        'Family Code',
        'Family Name'
      ]
      defaults += agreements.values
      defaults + ['Applicant Tags', 'Family Tags']
    end

    def content(applicant)
      data = [
        applicant.student&.code,
        applicant.student&.id,
        applicant.reviewed_prop(:first_name),
        applicant.reviewed_prop(:last_name),
        applicant.grade,
        grade_levels[applicant.grade],
        applicant.family.code,
        applicant.family.name
      ]

      applicant_agreements = applicant.applicant_agreements
      responses = applicant_agreements.map { |a| [a.agreement_id, a.decorate.action.titleize] }.to_h

      data += agreements.keys.map { |a| responses[a] || 'N/A' }
      data + [
        applicant.tags.map(&:name).join(', '),
        family_tags[applicant.family_id]&.tags&.map(&:name)&.join(', ')
      ]
    end
end
