require 'csv'

namespace :import do
  desc "Import OUI list (mac_prefix, manufacture, hostname) from CSV"
  task :oui_list, [:file_path, :organisation_id] => :environment do |t, args|
    file_path = args[:file_path]
    org_id = args[:organisation_id]

    if file_path.blank?
      puts "Error: file_path argument required. Usage: rake import:oui_list['/path/to/file.csv',ORG_ID]"
      next
    end
    if org_id.blank?
      puts "Error: organisation_id argument required. Usage: rake import:oui_list['/path/to/file.csv',ORG_ID]"
      next
    end
    file_path = Pathname.new(file_path)

    unless File.exist?(file_path)
      puts " File not found: #{file_path}"
      next
    end

    puts " Importing OUI list from #{file_path} for organisation_id #{org_id}..."

    imported = 0
    updated = 0

    CSV.foreach(file_path, headers: true) do |row|
      mac_prefix = row['mac prefix'].to_s.strip.downcase
      manufacture = row['manufacturer'].to_s.strip
      hostname = row['common name'].to_s.strip
  
      next if mac_prefix.blank? || manufacture.blank? || hostname.blank?

      record = KnownClientMacOUI.find_or_initialize_by(mac_prefix: mac_prefix, organisation_id: org_id)
      is_new = record.new_record?

      record.manufacture = manufacture
      record.hostname = hostname if hostname.present?
      record.save!

      if is_new
        imported += 1
      elsif record.previous_changes.any?
        updated += 1
      end
    end

    puts " Imported #{imported} new OUI records."
    puts "  Updated #{updated} existing records."
    puts " Total records: #{KnownClientMacOUI.where(organisation_id: org_id).count} for organisation_id #{org_id}"
  end
end
