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

  def index
    data = attachments.includes(:attachment).order(:position).map { |a| attachment_props(a) }
    render_success :ok, json: data
  end

  def create
    admissions_attachment = admissions_attachments.find(params[:attachment_id])
    attachment = attachments.build(attachment: admissions_attachment)
    if attachment.save
      render_success :ok, json: attachment_props(attachment)
    else
      render_error :unprocessable_entity, message: 'Something went wrong'
    end
  end

  def update
    if attachment.update(attachment_params)
      render_success :ok, json: attachment_props(attachment)
    else
      render_error :unprocessable_entity, errors: attachment
    end
  end

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

  private
    def attachments
      application.application_attachments
    end

    def attachment
      @attachment ||= attachments.find(params[:id])
    end

    def admissions_attachments
      current_school.admission_attachments
    end

    def attachment_params
      params.permit(:position)
    end

    def attachment_props(attachment)
      {
        id: attachment.id,
        name: attachment.attachment.name,
        position: attachment.position,
        attachment_id: attachment.attachment_id
      }
    end
end
