module Api
  class EnterpriseAttachmentController < BaseController
    class MissingImplementationError < StandardError; end
    class UnknownEnterpriseAuthorizationActionError < StandardError; end

    before_filter :load_enterprise

    respond_to :json

    def destroy
      return respond_with_conflict(error: destroy_attachment_does_not_exist_error_message) unless @enterprise.public_send("#{attachment_name}?")

      @enterprise.update_attributes!(attachment_name => nil)
      render json: @enterprise, serializer: Admin::EnterpriseSerializer, spree_current_user: spree_current_user
    end

    protected

    def attachment_name
      raise MissingImplementationError, "Method attachment_name should be defined"
    end

    def enterprise_authorize_action
      raise MissingImplementationError, "Method enterprise_authorize_action should be defined"
    end

    def load_enterprise
      @enterprise = Enterprise.find_by_permalink(params[:enterprise_id].to_s)
      raise UnknownEnterpriseAuthorizationActionError if enterprise_authorize_action.blank?

      authorize!(enterprise_authorize_action, @enterprise)
    end

    def destroy_attachment_does_not_exist_error_message
      I18n.t("api.enterprise_#{attachment_name}.destroy_attachment_does_not_exist")
    end
  end
end
