module Admin
  class AgentsController < ApplicationController
    before_action :authenticate_user!
    before_action -> { authenticate_role!(:admin) }

    def index
      @agents = User.agent.order(:created_at)

      if turbo_frame_request?
        @agents = @agents.search(params[:term]) if params[:term].present?
        render partial: "admin/agents/search_results",
               locals: { agents: @agents }
      else
        render :index
      end
    end

    def new
      @agent = User.agent.new
    end

    def edit
      @agent = User.agent.find(params[:id])
    end

    def create
      @agent = User.new(
        agent_params.merge(
          role: :agent,
          password: "test1234",
          password_confirmation: "test1234"
        )
      )

      respond_to do |format|
        if @agent.save
          format.html { redirect_to admin_agents_path, notice: t(".success") }
        else
          format.html { render :new, status: :unprocessable_entity }
        end
      end
    end

    def update
      @agent = User.agent.find(params[:id])
      @agent.update(agent_params)

      redirect_to admin_agents_path
    end

    private

    def agent_params
      params.require(:user).permit(:email, :first_name, :last_name, :can_close_service_center)
    end
  end
end
