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

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

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

  def update
    if applicant_agreement.update(agreement_params)
      render_success :ok, json: agreement_props(agreement)
    else
      render_error :unprocessable_entity, errors: agreement
    end
  end

  private
    def agreements
      @agreements ||= applicant.application.agreements.positioned
    end

    def applicant_agreement
      @applicant_agreement ||= applicant.applicant_agreements
        .find_or_initialize_by(agreement: agreement)
    end

    def agreement
      @agreement ||= application_agreement.agreement
    end

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

    def responses
      @responses ||= applicant.applicant_agreements.index_by(&:agreement_id)
    end

    def application_agreements
      @application_agreements ||= applicant.application_agreements.index_by(&:agreement_id)
    end

    def agreement_params
      params.permit(:response)
    end

    def agreement_props(agreement)
      {
        id: agreement.id,
        name: agreement.name,
        body: agreement.body,
        required: application_agreements[agreement.id].required,
        response: responses[agreement.id]&.response
      }
    end
end
