namespace :sync_outer_repo do
  desc "sync outer repository to gitlink"
  task done: :environment do
    file = ENV['file'] || "rcore-os_repo.xlsx"
    file = ENV['file'] || "openkylin.xlsx"
    user_type = ENV['type'] || "User"
    doc = SimpleXlsxReader.open("#{Rails.root}/public/#{file}")
    data = doc.sheets.first.rows
    data.each_with_index do |row, index|
      next if index == 0
      begin
        user = (user_type == "User" ? User.find_by(login: row[1]) : Owner.find_by(login: row[1]))
        project = user.projects.find_by(identifier: row[4])
        unless project.present?
          p_category = ProjectCategory.find_or_create_by(name: row[6])
          p_language = ProjectLanguage.find_or_create_by(name: row[7].to_s.split("/")[0]) if row[7]
          p_license = License.find_by(name: row[8])

          mirror_params = {
            user_id: user.id,
            name: row[5],
            description: row[9],
            repository_name: row[4],
            project_category_id: p_category.id,
            project_language_id: p_language&.id,
            clone_addr: row[10]
          }
          Projects::MigrateService.call(user, mirror_params)
        end
        puts "sync outer repository to gitlink Success repo: #{row[5]} username: #{row[0]}"
      rescue Exception => e
        puts "sync outer repository to gitlink Error repo: #{row[5]} username: #{row[0]}, error:#{e}"
      end
    end
  end
end