# frozen_string_literal: true

class UpdateGeoIpDatabaseJob < ApplicationJob
  queue_as :default

  # Schedule this job to run weekly to keep the GeoIP database updated
  # Use: UpdateGeoIpDatabaseJob.set(wait: 1.week).perform_later
  # Or set up in config/schedule.rb for recurring execution

  def perform(force_update: false)
    return unless auto_update_enabled?

    Rails.logger.info "Starting GeoIP database update check"

    if should_update_database? || force_update
      success = GeoIpService.update_database!

      if success
        Rails.logger.info "GeoIP database successfully updated"
      else
        Rails.logger.error "Failed to update GeoIP database"
      end
    else
      Rails.logger.info "GeoIP database is up to date, no update needed"
    end

    # No cleanup needed with file-system approach
  rescue => e
    Rails.logger.error "Error in UpdateGeoIpDatabaseJob: #{e.message}"
    Rails.logger.error e.backtrace.join("\n")
  end

  private

  def auto_update_enabled?
    Rails.application.config.maxmind.auto_update_enabled
  end

  def should_update_database?
    config = Rails.application.config.maxmind
    database_path = default_database_path

    # Check if database file exists
    return true unless File.exist?(database_path)

    # Check if database is outdated
    max_age_days = config.max_age_days
    file_mtime = File.mtime(database_path)
    return true if file_mtime < max_age_days.days.ago

    # Check if database file is readable and valid
    begin
      # Try to open the database to verify it's valid
      MaxMind::DB.new(database_path)
      false
    rescue => e
      Rails.logger.warn "GeoIP database file appears to be corrupted: #{e.message}"
      true
    end
  end

  def default_database_path
    config = Rails.application.config.maxmind
    File.join(config.storage_path, config.database_filename)
  end
end