module BeefCake
  class MembershipsController < BeefCake::BaseController
    before_action :set_membership, only: [:edit, :update, :destroy]

    def new
      @membership = Membership.new params
      authorize @membership
      set_back_url
    end

    def create
      @membership = Membership.new(params
        .require(:beef_cake_membership)
        .permit(:uid, :role_id, :expires_at))
      authorize @membership

      user = User.find(@membership.uid)
      respond_to do |format|
        if user.nil? || !user.exists?
          error_msg = "invalid user #{@membership.uid}"
          format.html { redirect_to new_beef_cake_membership_path, :flash => { :error => error_msg} }
          format.json { render json: error_msg, status: :unprocessable_entity}
        elsif @membership.save
          format.html { redirect_to edit_beef_cake_user_path(@membership.uid), :flash => { :success => "Success"}}
          format.json { render json: @membership, status: :created}
        else
          format.html { redirect_to new_beef_cake_membership_path, :flash => { :error => @membership.errors.full_messages.to_sentence}}
          format.json { render json: @membership.errors.full_messages.to_sentence, status: :unprocessable_entity}
        end
      end
    end

    def edit
      set_back_url
    end

    def update
      @membership.attributes = params
                               .require(:beef_cake_membership)
                               .permit(:expires_at)
      if @membership.save
        flash[:success] = "Success"
        redirect_to edit_beef_cake_user_path(@membership.uid)
      else
        flash[:error] = @membership.errors.full_messages.to_sentence
        redirect_to edit_beef_cake_membership_path(@membership.id)
      end
    end

    def destroy
      if @membership.destroy
        flash[:success] = "Success"
      else
        flash[:error] = @membership.errors.full_messages.to_sentence
      end

      redirect_back
    end

    protected

    def set_membership
      id = params[:id]
      id = "#{params[:id]}.#{params[:format]}" if params[:format]
      @membership = Membership.find id
      authorize @membership

      unless @membership.persisted?
        flash[:error] = @membership.errors.full_messages.to_sentence
        redirect_to edit_beef_cake_user_path(@membership.uid)
      end
    end

    def set_back_url
      @back_url = if @membership.uid.present?
                    edit_beef_cake_user_path(@membership.uid)
                  else
                    beef_cake_users_path
                  end
    end
  end
end
