class Api::V1::Users::DeleteUserService < ApplicationService
  attr_reader :user
  def initialize(user)
    @user = user
  end

  def call
    begin
      ActiveRecord::Base.transaction do
        org_ids = TeamUser.where(user_id: @user.id).pluck(:organization_id) | OrganizationUser.where(user_id: @user.id).pluck(:organization_id)
        organizations = Organization.where(id: org_ids)
        organizations.each do |org|
          # org.team_users.joins(:team).where(user_id: @user.id, teams: {authorize: %w(owner)})
          owner_count = org.team_users.joins(:team).where(teams: {authorize: %w(owner)}).count
          # 多个owner时,仅将用户从组织移除, 一个时直接删除
          org.team_users.where(user_id: @user.id).destroy_all
          org.organization_users.where(user_id: @user.id, organization_id: org.id).destroy_all
          if owner_count == 1
            if org.team_users.joins(:team).where(user_id: @user.id, teams: { authorize: %w(owner) }).count > 0
              org.destroy!
            end
          end
        end
        @user.destroy!
        del_user_data_by_sql(@user.id)
      end
      Gitea::User::DeleteService.call(@user.login, true)
      return true
    rescue
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  def del_user_data_by_sql(user_id)
    if ActiveRecord::Base.connection.table_exists?("memos")
      sql1 = "delete from memos where author_id=#{user_id}"
      ActiveRecord::Base.connection.execute(sql1)
    else
      Rails.logger.info "memos table does not exist"
    end
  end
end