namespace :sync_outer_repo_mirror do
  desc "sync outer repository to gitlink"
  task done: :environment do
    file = ENV['file'] || "openkylin2.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])
        new_date = project.present? ? project.created_on : (Time.now - rand(5..60).day - rand(5..30).hour)
        if project.present?
          ActiveRecord::Base.transaction do
            Gitea::Repository::DeleteService.new(project.owner, project.identifier).call
            project.destroy!
            project.forked_projects.update_all(forked_from_project_id: nil)
            # 如果该项目有所属的项目分类以及为私有项目，需要更新对应数量
            project.project_category.decrement!(:private_projects_count, 1) if project.project_category.present? && !project.is_public
          end
        end
        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,
          license_id: p_license&.id,
          is_mirror: true,
          clone_addr: row[10]
        }
        @project = Projects::MigrateService.call(user, mirror_params)

        @project.update_columns(created_on: new_date, updated_on: new_date)
        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