package pool

import (
	
	
	
	
)

// PubSubStats contains pub/sub connection pool stats.
//
// TODO(cxl): the uint32 fields below will be changed to atomic.Uint32 in v10,
// which is a breaking API change.
type PubSubStats struct {
	Created   uint32
	Untracked uint32
	Active    uint32
}

// PubSubPool manages a pool of PubSub connections.
type PubSubPool struct {
	opt       *Options
	netDialer func(ctx context.Context, network, addr string) (net.Conn, error)

	// Map to track active PubSub connections
	activeConns sync.Map // map[uint64]*Conn (connID -> conn)
	closed      atomic.Bool
	stats       PubSubStats
}

// NewPubSubPool implements a pool for PubSub connections.
// It intentionally does not implement the Pooler interface
func ( *Options,  func( context.Context, ,  string) (net.Conn, error)) *PubSubPool {
	return &PubSubPool{
		opt:       ,
		netDialer: ,
	}
}

func ( *PubSubPool) ( context.Context,  string,  string,  []string) (*Conn, error) {
	if .closed.Load() {
		return nil, ErrClosed
	}

	,  := .netDialer(, , )
	if  != nil {
		return nil, 
	}
	 := NewConnWithBufferSize(, .opt.ReadBufferSize, .opt.WriteBufferSize)
	.pubsub = true
	// Set pool name for metrics
	.SetPoolName(.opt.Name)
	atomic.AddUint32(&.stats.Created, 1)
	return , nil
}

func ( *PubSubPool) ( *Conn) {
	atomic.AddUint32(&.stats.Active, 1)
	.activeConns.Store(.GetID(), )
	// Emit +1 used for PubSub connection
	if  := getMetricConnectionCountCallback();  != nil {
		(context.Background(), 1, , "used", true)
	}
}

func ( *PubSubPool) ( *Conn) {
	// LoadAndDelete ensures each connection is only decremented once,
	// guarding against double-decrement if Close() already untracked it.
	if ,  := .activeConns.LoadAndDelete(.GetID()); ! {
		return
	}
	atomic.AddUint32(&.stats.Active, ^uint32(0))
	atomic.AddUint32(&.stats.Untracked, 1)
	// Emit -1 used for PubSub connection
	if  := getMetricConnectionCountCallback();  != nil {
		(context.Background(), -1, , "used", true)
	}
}

func ( *PubSubPool) () error {
	.closed.Store(true)
	 := getMetricConnectionCountCallback()
	.activeConns.Range(func(,  interface{}) bool {
		 := .(*Conn)
		// Use LoadAndDelete to atomically claim ownership of this entry.
		// If a concurrent UntrackConn already removed it, skip to avoid double-decrement.
		if ,  := .activeConns.LoadAndDelete(); ! {
			return true
		}
		atomic.AddUint32(&.stats.Active, ^uint32(0))
		atomic.AddUint32(&.stats.Untracked, 1)
		// Emit -1 used for each PubSub connection being closed
		if  != nil {
			(context.Background(), -1, , "used", true)
		}
		_ = .Close()
		return true
	})
	return nil
}

func ( *PubSubPool) () *PubSubStats {
	// load stats atomically
	return &PubSubStats{
		Created:   atomic.LoadUint32(&.stats.Created),
		Untracked: atomic.LoadUint32(&.stats.Untracked),
		Active:    atomic.LoadUint32(&.stats.Active),
	}
}