class MigrateRemoteRepositoryJob < ApplicationJob
  queue_as :default

  def perform(repo_id, token, user_id, params)
    repo = Repository.find_by(id: repo_id)
    return if repo.blank?

    puts "############ MigrateRemoteRepositoryJob starting ... ############"
    params.except!(:auth_password, :auth_username) if params[:auth_username].nil?
    gitea_repository = Gitea::Repository::MigrateService.new(token, params).call
    puts "#gitea_repository#{gitea_repository}"
    if gitea_repository[0]==201
      repo&.project&.update_columns(gpid: gitea_repository[2]["id"], default_branch: gitea_repository[2]["default_branch"])
      repo&.mirror&.succeeded!
      ## open jianmu devops
      project_id = repo&.project&.id
      puts "############ mirror project_id,user_id: #{project_id},#{user_id}  ############"
      # OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(project_id, user_id) if project_id.present? && user_id.present?
      UpdateProjectTopicJob.set(wait: 1.seconds).perform_later(project_id) if project_id.present?
      puts "############ mirror status: #{repo.mirror.status} ############"
    else 
      gitea_result = $gitea_client.get_repos_by_owner_repo(repo&.project&.owner&.login, repo&.project&.identifier)
      if gitea_result["empty"]
        repo&.mirror&.failed!
        repo&.project&.update_columns(status: 0)
      else
        repo&.project&.update_columns(gpid: gitea_repository[2]["id"], default_branch: gitea_repository[2]["default_branch"])
        repo&.mirror&.succeeded!
        project_id = repo&.project&.id
        puts "############ mirror project_id,user_id: #{project_id},#{user_id}  ############"
        # OpenProjectDevOpsJob.set(wait: 5.seconds).perform_later(project_id, user_id) if project_id.present? && user_id.present?
        # 导入成功后删除镜像仓库流水线启用配置
        Gitea::RepoUnit.where(repo_id: gitea_repository[2]["id"], type: 10).destroy_all if repo.is_mirror?
        UpdateProjectTopicJob.set(wait: 1.seconds).perform_later(project_id) if project_id.present?
        puts "############ mirror status: #{repo.mirror.status} ############"
      end
    end
    # UpdateProjectTopicJob 中语言要延迟1S才能获取
    BroadcastMirrorRepoMsgJob.set(wait: 10.seconds).perform_later(repo.id) unless repo&.mirror.waiting?
  end
end
