class Admin::Admissions::Applications::DocumentsController < Admin::Admissions::Controller
  include Admin::Admissions::ApplicationScoped

  def index
    data = documents.includes(:document).order(:position).map { |d| document_props(d) }
    render_success :ok, json: data
  end

  def create
    admissions_document = admissions_documents.find(params[:document_id])
    document = documents.build(document: admissions_document)
    if document.save
      render_success :ok, json: document_props(document)
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

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

  def destroy
    if document.destroy
      render_success :ok, event: :removed
    else
      render_error :unprocessable_entity, errors: document
    end
  end

  private
    def documents
      application.application_documents
    end

    def document
      @document ||= documents.find(params[:id])
    end

    def admissions_documents
      current_school.admission_documents
    end

    def document_params
      params.permit(:position, :required)
    end

    def document_props(document)
      {
        id: document.id,
        name: document.document.name,
        required: document.required,
        position: document.position,
        document_id: document.document_id
      }
    end
end
