# frozen_string_literal: true

# ExpiredRulesCleanupJob - Disables rules that have expired
#
# This job runs periodically (hourly) to find rules with expires_at in the past
# and disables them. Agents will pick up these disabled rules in their next sync
# and remove them from their local evaluation tables.
#
# Schedule: Every hour (configured in initializer or cron)
class ExpiredRulesCleanupJob < ApplicationJob
  queue_as :default

  def perform
    expired_rules = Rule.enabled.expired

    Rails.logger.info "ExpiredRulesCleanupJob: Found #{expired_rules.count} expired rules"

    return if expired_rules.empty?

    # Disable all expired rules in a single update
    count = expired_rules.update_all(
      enabled: false,
      updated_at: Time.current
    )

    Rails.logger.info "ExpiredRulesCleanupJob: Disabled #{count} expired rules"

    # Optionally: Clean up old disabled rules after a retention period
    cleanup_old_disabled_rules if should_cleanup_old_rules?

    count
  end

  private

  def should_cleanup_old_rules?
    # Only cleanup on first hour of the day to avoid too frequent deletion
    Time.current.hour == 1
  end

  def cleanup_old_disabled_rules
    # Delete disabled rules older than 30 days (keep for audit trail)
    old_rules = Rule.disabled.where("updated_at < ?", 30.days.ago)

    if old_rules.any?
      count = old_rules.delete_all
      Rails.logger.info "ExpiredRulesCleanupJob: Deleted #{count} old disabled rules (>30 days)"
    end
  end
end
