module RegisterHelper
  extend ActiveSupport::Concern

  def autologin_register(username, email, password, platform = 'forge', phone = nil, nickname =nil, need_edit_info = false)
    result = {message: nil, user: nil}

    user.password = password
    user.platform = platform
    user.phone = phone if phone.present?
    user.nickname = nickname if nickname.present?
    if need_edit_info
      user.need_edit_info
    else
      user.activate
    end

    return unless user.valid?

    interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
    # Rails.logger.info "interactor===#{interactor.success?}"
    # Rails.logger.info "interactor===#{interactor.result}"
    result ={}
    if interactor.success?
      gitea_user = interactor.result
      result = Gitea::User::GenerateTokenService.call(username, password)
      user.gitea_token = result['sha1']
      user.gitea_uid = gitea_user[:body]['id'] if gitea_user[:body].present?
      if user.save!
        UserExtension.create!(user_id: user.id) if user.user_extension.blank?
        result[:user] = {id: user.id, token: user.gitea_token}
      end
    else
      result[:message] = interactor.result[:message]
    end
    result
  end

  def auto_update(user, params={})
    return if params.blank?
    result = {message: nil, user: nil}
    before_login = user.login
    user.login = params[:username]
    user.password = params[:password]
    user.mail = params[:email]

    if user.save!
      sync_params = {
        password: params[:password].to_s,
        email: params[:email],
        login_name: params[:username],
        new_name: params[:username],
        source_id: 0
      }

      interactor = Gitea::User::UpdateInteractor.call(before_login, sync_params)
      if interactor.success?
        result[:user] = user
      else
        result[:message] = '用户同步Gitea失败!'
      end
    else
      result[:message] = user.errors.full_messages.join(",")
      return
    end
  end
end
