class BotsController < ApplicationController
  before_action :set_bot, only: %i[ show edit update destroy telegram_listen ]

  # GET /bots or /bots.json
  def index
    authorize @bots = policy_scope(Bot)
  end

  # GET /bots/1 or /bots/1.json
  def show
    authorize @bot
  end

  # GET /bots/new
  def new
    authorize @bot = current_user.bots.new
  end

  # GET /bots/1/edit
  def edit
    authorize @bot
  end

  def telegram_listen
    authorize @bot 
    @bot.delay.telegram_listen
    redirect_to request.referrer 
  end

  # POST /bots or /bots.json
  def create
    authorize @bot = Bot.new(bot_params)

    respond_to do |format|
      if @bot.save
        format.html { redirect_to bot_url(@bot), notice: "Bot was successfully created." }
        format.json { render :show, status: :created, location: @bot }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @bot.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /bots/1 or /bots/1.json
  def update
    authorize @bot
    respond_to do |format|
      if @bot.update(bot_params)
        format.html { redirect_to bot_url(@bot), notice: "Bot was successfully updated." }
        format.json { render :show, status: :ok, location: @bot }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @bot.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /bots/1 or /bots/1.json
  def destroy
    @bot.destroy

    respond_to do |format|
      format.html { redirect_to bots_url, notice: "Bot was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_bot
      @bot = Bot.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def bot_params
      params.require(:bot).permit(:name, :telegram_api_token, :discord_api_token, :user_id, :profile_id)
    end
end
