class Admin::Admissions::AttachmentsController < Admin::Admissions::Controller
  def index
    data = attachments.by_archived(params[:archived]&.to_bool).sorted
    render_success :ok, json: data.map { |d| attachment_props(d) }
  end

  def show
    render_success :ok, json: attachment_props(attachment)
  end

  def create
    attachment = attachments.build(attachment_params)
    if attachment.save
      render_success :ok, json: attachment_props(attachment)
    else
      render_error :unprocessable_entity, errors: attachment
    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
    else
      render_error :unprocessable_entity, errors: attachment
    end
  end

  private
    def attachments
      current_school.admission_attachments
    end

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

    def attachment_params
      params.permit(:name, :archived, :description, :file)
    end

    def attachment_props(attachment)
      {
        id: attachment.id,
        name: attachment.name,
        filename: attachment.file.attachment&.filename,
        description: attachment.description,
        archived: attachment.archived,
        url: attachment.file.attachment&.service_url
      }
    end
end
