# typed: true
class State::IpAddressRolesController < ApplicationController
  before_action :set_ip_address_role, only: %i[edit update destroy toggle]
  before_action :authorize_ip_address_roles

  # GET /state/ip_address_roles
  def index
    @ip_address_roles = IpAddressRole.all.order(created_at: :desc)
  end

  # GET /state/ip_address_roles/new
  def new
    @ip_address_role = IpAddressRole.new
  end

  # GET /state/ip_address_roles/1/edit
  def edit
  end

  # POST /state/ip_address_roles
  def create
    @ip_address_role = IpAddressRole.new(ip_address_role_params)

    if @ip_address_role.save
      redirect_to state_ip_address_roles_path,
                  notice: "IP address role was successfully created."
    else
      render :new
    end
  end

  # PATCH/PUT /state/ip_address_roles/1
  def update
    if @ip_address_role.update(ip_address_role_params)
      redirect_to state_ip_address_roles_path,
                  notice: "IP address role was successfully updated."
    else
      render :edit
    end
  end

  # DELETE /state/ip_address_roles/1
  def destroy
    @ip_address_role.destroy
    redirect_to state_ip_address_roles_path,
                notice: "IP address role was successfully deleted."
  end

  def toggle
    @ip_address_role.update!(active: !@ip_address_role.active)
    redirect_to state_ip_address_roles_path
  rescue ActiveRecord::RecordInvalid => e
    redirect_to state_ip_address_roles_path,
                alert: "Failed to update status: #{e.message}"
  end

  private

  # Use callbacks to share common setup or constraints between actions
  def set_ip_address_role
    @ip_address_role = IpAddressRole.find(params[:id])
  end

  # Only allow a list of trusted parameters through
  def ip_address_role_params
    params.require(:ip_address_role).permit(
      :ip_address,
      :role,
      :description,
      :active,
    )
  end

  # Authorize all actions based on the current action
  def authorize_ip_address_roles
    case action_name.to_sym
    when :index, :new, :edit
      authorize IpAddressRole, policy_class: State::IpAddressRolePolicy
    when :create
      authorize IpAddressRole, policy_class: State::IpAddressRolePolicy
    when :update, :destroy, :toggle
      authorize @ip_address_role, policy_class: State::IpAddressRolePolicy
    end
  end
end
