namespace :repair_gitea_user do
  desc "If forge users gitea_uid is null repair gitea user"
  task done: :environment do
    users = User.find_by_sql("SELECT * FROM `users` WHERE id !=2 AND type='User' AND NOT EXISTS (SELECT * FROM forgegitea.`user` WHERE forgegitea.`user`.id=users.gitea_uid)")
    puts "total users count:#{users.count}"
    success_count = 0
    users.each do |user|
      begin
        interactor = Gitea::RegisterInteractor.call({ username: user.login, email: user.mail, password: "abc12345678" })
        if interactor.success?
          gitea_user = interactor.result
          result = Gitea::User::GenerateTokenService.call(user.login, password)
          user.gitea_token = result['sha1']
          user.gitea_uid = gitea_user[:body]['id']
          user.is_sync_pwd = false
          user.save!
          success_count = success_count + 1
        end
      rescue Exception => e
        puts "repair gitea user: #{user.id}:#{user.login}:, error:#{e}"
      end
    end
    puts "repair gitea user success total: #{success_count}"
  end
end