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}
    email =  email.blank? ? "#{username}@example.org" : email

    user = User.new(admin: false, login: username, mail: email, type: "User")
    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})
    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 autosync_register_trustie(username, password, email, lastname="")
    config = Rails.application.config_for(:configuration).symbolize_keys!

    api_host = config[:sync_url]

    return if api_host.blank?

    url = "#{api_host}/api/v1/users/common"
    sync_json = {
      "mail": email,
      "password": password,
      "login": username,
      "lastname": lastname
    }.compact
    uri = URI.parse(url)

    if api_host
      http = Net::HTTP.new(uri.hostname, uri.port)

      if api_host.include?("https://")
        http.use_ssl = true
      end

      http.send_request('POST', uri.path, sync_json.to_json, {'Content-Type' => 'application/json'})
    end
  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
