class Api::V1::Users::UpdateEmailService < ApplicationService 
  include ActiveModel::Model 
  include AesCryptHelper

  attr_reader :user, :token, :password, :mail, :old_mail, :code, :verify_code
  attr_accessor :gitea_data

  validates :password, :code, presence: true
  validates :mail, presence: true, format: { with: CustomRegexp::EMAIL }

  def initialize(user, params, token =nil)
    @user = user 
    @token = token 
    @password = decrypt(params[:password]) rescue params[:password].to_s
    @mail = params[:email]
    @old_mail = user.mail
    @code = params[:code]
    @verify_code = VerificationCode.where(email: @mail, code_type: 10).last
  end

  def call 
    raise Error, "此用户禁止修改邮箱." if @user.id.to_i === 104691
    raise Error, errors.full_messages.join(",") unless valid? 
    raise Error, "密码不正确." unless @user.check_password?(@password)
    exist_owner = Owner.find_by(mail: @mail)
    raise Error, "邮箱已被使用." if exist_owner 
    is_debug =  @code == "123123" && EduSetting.get("code_debug") # 万能验证码，用于测试 # TODO 万能验证码，用于测试
    raise Error, "验证码不正确." if @verify_code&.code != @code && !is_debug
    raise Error, "验证码已失效." if !@verify_code&.effective? && !is_debug

    begin
      ActiveRecord::Base.transaction do
        change_user_email 
        excute_data_to_gitea 
        excute_change_email_from_gitea 
        remove_old_cache_for_user
      end

      return gitea_data

    rescue
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  private 
  def request_params
    {
      access_token: @user.gitea_token
    }
  end

  def request_body 
    {
      email: @mail,
      login_name: @user.login,
      source_id: 0
    }
  end

  def change_user_email
    @user.update_attributes!({mail: @mail})
  end

  def excute_data_to_gitea 
    @gitea_data = $gitea_client.patch_admin_users_by_username(@user.login, {body: request_body.to_json})
  end

  def excute_change_email_from_gitea
    emails = $gitea_client.get_user_emails({query: request_params})
    puts "emails=#{emails}"
    emails.each do |email|
      email = email.stringify_keys
      next if email["email"] == @mail 
      $gitea_client.delete_user_emails({body: {emails: [email["email"]]}.to_json, query: request_params})
    end
  end

  def remove_old_cache_for_user
    $redis_cache.del("v2-owner-common:#{@user.login}-#{@old_mail}")
  end
end