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

  def index
    render_success :ok, json: documents.map { |e| document_props(e) }
  end

  def show
    render_success :ok, json: document_props(document)
  end

  def update
    if applicant_document.update(document_params)
      render_success :ok, json: document_props(document)
    else
      render_error :unprocessable_entity, errors: applicant_document
    end
  end

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

    def applicant_document
      @applicant_document ||= applicant.applicant_documents
        .find_or_initialize_by(document: document)
    end

    def application_document
      @application_document ||= applicant.application.application_documents
        .find_by(document_id: params[:document_id])
    end

    def document
      @document ||= application_document.document
    end

    def application_documents
      @application_documents ||= applicant.application.application_documents.index_by(&:document_id)
    end

    def applicant_documents
      @applicant_documents ||= applicant.applicant_documents.index_by(&:document_id)
    end

    def document_params
      params.permit(:file)
    end

    def document_props(document)
      {
        id: document.id,
        name: document.name,
        description: document.description,
        required: application_documents[document.id].required,
        filename: applicant_documents[document.id]&.file&.attachment&.filename,
        url: applicant_documents[document.id]&.file&.attachment&.service_url
      }
    end
end
