Rails.application.routes.draw do
  # Registration only allowed when no users exist
  resource :registration, only: [:new, :create]
  resource :session
  resource :password

  # OIDC authentication routes (explicit, no middleware)
  post "/auth/oidc", to: "oidc_auth#authorize"
  get "/auth/oidc/callback", to: "oidc_auth#callback"

  # Admin user management (admin only)
  resources :users, only: [:index, :show, :edit, :update]

  # Settings management (admin only)
  resources :settings, only: [:index] do
    collection do
      patch :update
    end
  end

  # DSN management (admin only)
  resources :dsns do
    member do
      post :disable
      post :enable
    end
  end

  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
  # Can be used by load balancers and uptime monitors to verify that the app is live.
  get "up" => "rails/health#show", as: :rails_health_check

  # WAF API
  namespace :api, defaults: { format: :json } do
    # Event ingestion (PRIMARY method - includes rule updates in response)
    post "events", to: "events#create"

    # Rule synchronization (SECONDARY - for admin/debugging only)
    # Note: Agents should use event responses for rule synchronization
    get "rules/version", to: "rules#version"
    get "rules", to: "rules#index"
  end

  # Analytics dashboard
  get "analytics", to: "analytics#index"
  get "analytics/networks", to: "analytics#networks"

  # Root path - analytics dashboard
  root "analytics#index"

  # Event management
  resources :events, only: [:index, :show]

  # Network range management
  resources :network_ranges, only: [:index, :show, :new, :create, :edit, :update, :destroy] do
    member do
      post :enrich
    end
    collection do
      get :lookup
      get :search
    end
  end

  # Support CIDR patterns with dots in network range routes
  get '/network_ranges/:id', to: 'network_ranges#show', constraints: { id: /[\d\.:\/_]+/ }

  # Rule management
  resources :rules, only: [:index, :new, :create, :show, :edit, :update] do
    member do
      post :disable
      post :enable
    end
  end

  # WAF Policy management
  resources :waf_policies, only: [:index, :new, :create, :show, :edit, :update, :destroy] do
    member do
      post :activate
      post :deactivate
    end
    collection do
      get :new_country
      post :create_country
    end
  end

  # GeoLite2 data import management (admin only)
  resources :data_imports, only: [:index, :new, :create, :show, :destroy] do
    member do
      get :progress
    end
  end
end
