class Admin::Admissions::Applicants::AgreementsController < Admin::Admissions::Controller
  include Admin::Admissions::ApplicantScoped

  def index
    render_success :ok, json: application_agreements.map { |a| agreement_props(a) }
  end

  def show
    render_success :ok, json: agreement_props(application_agreement)
  end

  def destroy
    if applicant_agreement.destroy
      render_success :ok, json: agreement_props(application_agreement)
    else
      render_error :unprocessable_entity, errors: applicant_agreement
    end
  end

  private
    def applicant_agreements
      applicant.applicant_agreements
    end

    def applicant_agreement
      @applicant_agreement ||= applicant_agreements.find_by(agreement_id: params[:id])
    end

    def application_agreements
      applicant.application.agreements.positioned
    end

    def application_agreement
      @application_agreement ||= application_agreements.find_by(id: params[:id])
    end

    def responses
      @responses ||= applicant_agreements.map { |a| [a.agreement.id, a.response] }.to_h
    end

    def family
      @family ||= applicant.family
    end

    def agreement_props(agreement)
      {}.tap do |prop|
        prop[:id] = agreement.id
        prop[:name] = agreement.name
        prop[:response] = responses[agreement.id]
        prop[:body] = agreement.body
        prop[:family_name] = family.name
      end
    end
end
