package maintnotifications

import (
	
	
	
	

	
	
	
)

// OperationsManagerInterface defines the interface for completing handoff operations
type OperationsManagerInterface interface {
	TrackMovingOperationWithConnID(ctx context.Context, newEndpoint string, deadline time.Time, seqID int64, connID uint64) error
	UntrackOperationWithConnID(seqID int64, connID uint64)
}

type maintNotificationsConnTracker interface {
	UntrackMaintNotificationsConn(connID uint64)
}

// HandoffRequest represents a request to handoff a connection to a new endpoint
type HandoffRequest struct {
	Conn     *pool.Conn
	ConnID   uint64 // Unique connection identifier
	Endpoint string
	SeqID    int64
	Pool     pool.Pooler // Pool to remove connection from on failure
}

// PoolHook implements pool.PoolHook for Redis-specific connection handling
// with maintenance notifications support.
type PoolHook struct {
	// Base dialer for creating connections to new endpoints during handoffs
	// args are network and address
	baseDialer func(context.Context, string, string) (net.Conn, error)

	// Network type (e.g., "tcp", "unix")
	network string

	// Worker manager for background handoff processing
	workerManager *handoffWorkerManager

	// Configuration for the maintenance notifications
	config *Config

	// Operations manager interface for operation completion tracking
	operationsManager OperationsManagerInterface

	// Pool interface for removing connections on handoff failure
	pool pool.Pooler
}

// NewPoolHook creates a new pool hook
func ( func(context.Context, string, string) (net.Conn, error),  string,  *Config,  OperationsManagerInterface) *PoolHook {
	return NewPoolHookWithPoolSize(, , , , 0)
}

// NewPoolHookWithPoolSize creates a new pool hook with pool size for better worker defaults
func ( func(context.Context, string, string) (net.Conn, error),  string,  *Config,  OperationsManagerInterface,  int) *PoolHook {
	// Apply defaults if config is nil or has zero values
	if  == nil {
		 = .ApplyDefaultsWithPoolSize()
	}

	 := &PoolHook{
		// baseDialer is used to create connections to new endpoints during handoffs
		baseDialer:        ,
		network:           ,
		config:            ,
		operationsManager: ,
	}

	// Create worker manager
	.workerManager = newHandoffWorkerManager(, )

	return 
}

// SetPool sets the pool interface for removing connections on handoff failure
func ( *PoolHook) ( pool.Pooler) {
	.pool = 
}

// GetCurrentWorkers returns the current number of active workers (for testing)
func ( *PoolHook) () int {
	return .workerManager.getCurrentWorkers()
}

// IsHandoffPending returns true if the given connection has a pending handoff
func ( *PoolHook) ( *pool.Conn) bool {
	return .workerManager.isHandoffPending()
}

// GetPendingMap returns the pending map for testing purposes
func ( *PoolHook) () *sync.Map {
	return .workerManager.getPendingMap()
}

// GetMaxWorkers returns the max workers for testing purposes
func ( *PoolHook) () int {
	return .workerManager.getMaxWorkers()
}

// GetHandoffQueue returns the handoff queue for testing purposes
func ( *PoolHook) () chan HandoffRequest {
	return .workerManager.getHandoffQueue()
}

// GetCircuitBreakerStats returns circuit breaker statistics for monitoring
func ( *PoolHook) () []CircuitBreakerStats {
	return .workerManager.getCircuitBreakerStats()
}

// ResetCircuitBreakers resets all circuit breakers (useful for testing)
func ( *PoolHook) () {
	.workerManager.resetCircuitBreakers()
}

// OnGet is called when a connection is retrieved from the pool
func ( *PoolHook) ( context.Context,  *pool.Conn,  bool) ( bool,  error) {
	// Check if connection is marked for handoff
	// This prevents using connections that have received MOVING notifications
	if .ShouldHandoff() {
		return false, ErrConnectionMarkedForHandoffWithState
	}

	// Check if connection is usable (not in UNUSABLE or CLOSED state)
	// This ensures we don't return connections that are currently being handed off or re-authenticated.
	if !.IsUsable() {
		return false, ErrConnectionMarkedForHandoff
	}

	return true, nil
}

// OnPut is called when a connection is returned to the pool
func ( *PoolHook) ( context.Context,  *pool.Conn) ( bool,  bool,  error) {
	// first check if we should handoff for faster rejection
	if !.ShouldHandoff() {
		// Default behavior (no handoff): pool the connection
		return true, false, nil
	}

	// check pending handoff to not queue the same connection twice
	if .workerManager.isHandoffPending() {
		// Default behavior (pending handoff): pool the connection
		return true, false, nil
	}

	if  := .workerManager.queueHandoff();  != nil {
		// Failed to queue handoff, remove the connection
		internal.Logger.Printf(, "%s", logs.FailedToQueueHandoff(.GetID(), ))
		// Don't pool, remove connection, no error to caller
		return false, true, nil
	}

	// Check if handoff was already processed by a worker before we can mark it as queued
	if !.ShouldHandoff() {
		// Handoff was already processed - this is normal and the connection should be pooled
		return true, false, nil
	}

	if  := .MarkQueuedForHandoff();  != nil {
		// Marking can fail if a worker advanced the connection's state between
		// our queueHandoff above and here. Re-check ShouldHandoff: with the CAS
		// rollback in Conn.MarkQueuedForHandoff, a worker that already cleared
		// the handoff state is no longer misreported as ShouldHandoff=true, so a
		// cleared connection is reliably detected and pooled here.
		if !.ShouldHandoff() {
			// Handoff was processed - this is normal, pool the connection.
			return true, false, nil
		}
		// Still marked for handoff in an ambiguous state — remove it rather than
		// returning a connection a queued worker may still close or replace.
		return false, true, nil
	}
	internal.Logger.Printf(, "%s", logs.MarkedForHandoff(.GetID()))
	return true, false, nil
}

func ( *PoolHook) ( context.Context,  *pool.Conn,  error) {
	if ,  := .operationsManager.(maintNotificationsConnTracker);  &&  != nil {
		.UntrackMaintNotificationsConn(.GetID())
	}
}

// Shutdown gracefully shuts down the processor, waiting for workers to complete
func ( *PoolHook) ( context.Context) error {
	return .workerManager.shutdownWorkers()
}