# frozen_string_literal: true

class EventsController < ApplicationController
  def show
    @event = Event.includes(:network_range).find(params[:id])

    # Use denormalized network_range_id if available (much faster)
    @network_range = @event.network_range

    # Fallback to IP lookup if network_range_id is missing
    unless @network_range
      @network_range = NetworkRange.contains_ip(@event.ip_address.to_s).first

      # Auto-generate network range if no match found
      unless @network_range
        @network_range = NetworkRangeGenerator.find_or_create_for_ip(@event.ip_address)
        Rails.logger.debug "Auto-generated network range #{@network_range&.cidr} for IP #{@event.ip_address}" if @network_range
      end
    end
  end

  def index
    @events = Event.includes(:network_range, :rule).order(timestamp: :desc)
    Rails.logger.debug "Found #{@events.count} total events"
    Rails.logger.debug "Action: #{params[:waf_action]}"

    # Apply filters
    @events = @events.by_ip(params[:ip]) if params[:ip].present?
    @events = @events.by_waf_action(params[:waf_action]) if params[:waf_action].present?
    @events = @events.by_country(params[:country]) if params[:country].present?
    @events = @events.where(rule_id: params[:rule_id]) if params[:rule_id].present?

    # Network-based filters (now using denormalized columns)
    @events = @events.by_company(params[:company]) if params[:company].present?
    @events = @events.by_network_type(params[:network_type]) if params[:network_type].present?
    @events = @events.by_asn(params[:asn]) if params[:asn].present?
    @events = @events.by_network_cidr(params[:network_cidr]) if params[:network_cidr].present?

    Rails.logger.debug "Events count after filtering: #{@events.count}"

    # Debug info
    Rails.logger.debug "Events count before pagination: #{@events.count}"

    # Paginate
    @pagy, @events = pagy(@events, items: 50)

    # Network ranges are now preloaded via includes(:network_range)
    # The denormalized network_range_id makes this much faster than IP containment lookups

    Rails.logger.debug "Events count after pagination: #{@events.count}"
    Rails.logger.debug "Pagy info: #{@pagy.count} total, #{@pagy.pages} pages"
  end
end