namespace :release_assets do
  desc "Verify that legacy Release path columns match release_assets rows"
  task verify: :environment do
    unless Release.column_names.include?("cartridge_path")
      puts "A legacy path oszlopok már törölve vannak (DropLegacyPathColumnsFromReleases lefutott) — nincs mit ellenőrizni."
      exit 0
    end

    mapping = {
      "cartridge_path"   => "cartridge",
      "source_path"      => "source",
      "html_folder_path" => "html",
      "docs_folder_path" => "docs"
    }

    ok = true
    mapping.each do |column, kind|
      legacy = Release.unscoped.where.not(column => [ nil, "" ])
      assets = ReleaseAsset.unscoped.where(kind: kind)
      missing = legacy.where.not(id: assets.select(:release_id))
      mismatched = legacy
        .joins("INNER JOIN release_assets ra ON ra.release_id = releases.id AND ra.kind = '#{kind}'")
        .where("ra.path <> releases.#{column}")

      puts format("%-18s legacy: %4d  asset: %4d  missing: %d  mismatch: %d",
                  column, legacy.count, assets.count, missing.count, mismatched.count)
      missing.limit(10).each { |r| puts "  MISSING  release ##{r.id} (#{column}=#{r.public_send(column)})" }
      mismatched.limit(10).each { |r| puts "  MISMATCH release ##{r.id} (#{column}=#{r.public_send(column)})" }
      ok &&= missing.count.zero? && mismatched.count.zero?
    end

    if ok
      puts "OK: every legacy path column is mirrored in release_assets."
    else
      abort "FAIL: legacy path columns and release_assets differ."
    end
  end
end
