package maintnotifications

import (
	
	
	
	
	

	
	
	
	
)

// NotificationHandler handles push notifications for the simplified manager.
type NotificationHandler struct {
	manager           *Manager
	operationsManager OperationsManagerInterface
}

// HandlePushNotification processes push notifications with hook support.
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() == 0 {
		internal.Logger.Printf(, "%s", logs.InvalidNotificationFormat())
		return ErrInvalidNotification
	}

	,  := [0].(string)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidNotificationTypeFormat([0]))
		return ErrInvalidNotification
	}

	// Process pre-hooks - they can modify the notification or skip processing
	,  := .manager.processPreHooks(, , , )
	if ! {
		return nil // Hooks decided to skip processing
	}

	var  error
	switch  {
	case NotificationMoving:
		 = .handleMoving(, , )
	case NotificationMigrating:
		 = .handleMigrating(, , )
	case NotificationMigrated:
		 = .handleMigrated(, , )
	case NotificationFailingOver:
		 = .handleFailingOver(, , )
	case NotificationFailedOver:
		 = .handleFailedOver(, , )
	case NotificationSMigrating:
		 = .handleSMigrating(, , )
	case NotificationSMigrated:
		 = .handleSMigrated(, , )
	default:
		// Ignore other notification types (e.g., pub/sub messages)
		 = nil
	}

	// Record maintenance notification metric
	if  := pool.GetMetricMaintenanceNotificationCallback();  != nil {
		if ,  := .Conn.(*pool.Conn);  {
			(, , )
		}
	}

	// Process post-hooks with the result
	.manager.processPostHooks(, , , , )

	return 
}

// handleMoving processes MOVING notifications.
// MOVING indicates that a connection should be handed off to a new endpoint.
// This is a per-connection notification that triggers connection handoff.
// Expected format: ["MOVING", seqNum, timeS, endpoint]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 3 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("MOVING", ))
		return ErrInvalidNotification
	}
	,  := [1].(int64)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidSeqIDInMovingNotification([1]))
		return ErrInvalidNotification
	}

	// Extract timeS
	,  := [2].(int64)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidTimeSInMovingNotification([2]))
		return ErrInvalidNotification
	}

	 := ""
	if len() > 3 {
		// Extract new endpoint
		,  = [3].(string)
		if ! {
			 := fmt.Sprintf("%v", [3])
			// this could be <nil> which is valid
			if [3] == nil ||  == internal.RedisNull {
				 = ""
			} else {
				internal.Logger.Printf(, "%s", logs.InvalidNewEndpointInMovingNotification([3]))
				return ErrInvalidNotification
			}
		}
	}

	// Get the connection that received this notification
	 := .Conn
	if  == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("MOVING"))
		return ErrInvalidNotification
	}

	// Type assert to get the underlying pool connection
	var  *pool.Conn
	if ,  := .(*pool.Conn);  {
		 = 
	} else {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("MOVING", , ))
		return ErrInvalidNotification
	}

	// If the connection is closed or not pooled, we can ignore the notification
	// this connection won't be remembered by the pool and will be garbage collected
	// Keep pubsub connections around since they are not pooled but are long-lived
	// and should be allowed to handoff (the pubsub instance will reconnect and change
	// the underlying *pool.Conn)
	if (.IsClosed() || !.IsPooled()) && !.IsPubSub() {
		return nil
	}

	 := time.Now().Add(time.Duration() * time.Second)
	// If newEndpoint is empty, we should schedule a handoff to the current endpoint in timeS/2 seconds
	if  == "" ||  == internal.RedisNull {
		if internal.LogLevel.DebugOrAbove() {
			internal.Logger.Printf(, "%s", logs.SchedulingHandoffToCurrentEndpoint(.GetID(), float64()/2))
		}
		// same as current endpoint
		 = .manager.options.GetAddr()
		// delay the handoff for timeS/2 seconds to the same endpoint
		// do this in a goroutine to avoid blocking the notification handler
		// NOTE: This timer is started while parsing the notification, so the connection is not marked for handoff
		// and there should be no possibility of a race condition or double handoff.
		time.AfterFunc(time.Duration(/2)*time.Second, func() {
			if  == nil || .IsClosed() {
				return
			}
			if  := .markConnForHandoff(, , , );  != nil {
				// Log error but don't fail the goroutine - use background context since original may be cancelled
				internal.Logger.Printf(context.Background(), "%s", logs.FailedToMarkForHandoff(.GetID(), ))
				return
			}

			// Queue the handoff immediately if the connection is idle in the pool.
			// If the connection is in use (StateInUse), it will be queued when returned to the pool via OnPut.
			// This handles the case where the connection is idle and might never be retrieved again.
			if .GetStateMachine().GetState() == pool.StateIdle {
				// Queue on the hook that owns this connection's pool, not
				// unconditionally on the primary one: the request carries the
				// hook's pool, and a failed handoff removes the connection
				// from it — for a dedicated pipeline-pool connection the
				// primary pool cannot do that, which would close the
				// connection while leaving a dead slot behind.
				 := .manager.hookForConn()
				if  != nil && .workerManager != nil {
					if  := .workerManager.queueHandoff();  != nil {
						internal.Logger.Printf(context.Background(), "%s", logs.FailedToQueueHandoff(.GetID(), ))
					} else {
						// Mark the connection as queued for handoff to prevent it from being retrieved
						// This transitions the connection to StateUnusable
						if  := .MarkQueuedForHandoff();  != nil {
							internal.Logger.Printf(context.Background(), "%s", logs.FailedToMarkForHandoff(.GetID(), ))
						} else {
							internal.Logger.Printf(context.Background(), "%s", logs.MarkedForHandoff(.GetID()))
						}
					}
				}
			}
			// If connection is StateInUse, the handoff will be queued when it's returned to the pool
		})
		return nil
	}

	return .markConnForHandoff(, , , )
}

func ( *NotificationHandler) ( *pool.Conn,  string,  int64,  time.Time) error {
	if  := .MarkForHandoff(, );  != nil {
		internal.Logger.Printf(context.Background(), "%s", logs.FailedToMarkForHandoff(.GetID(), ))
		// Connection is already marked for handoff, which is acceptable
		// This can happen if multiple MOVING notifications are received for the same connection
		return nil
	}
	// Optionally track in m
	if .operationsManager != nil {
		 := .GetID()
		// Track the operation (ignore errors since this is optional)
		_ = .operationsManager.TrackMovingOperationWithConnID(context.Background(), , , , )
	} else {
		return errors.New(logs.ManagerNotInitialized())
	}
	return nil
}

// handleMigrating processes MIGRATING notifications.
// MIGRATING indicates that a connection migration is starting.
// This is a per-connection notification that applies relaxed timeouts.
// Expected format: ["MIGRATING", ...]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 2 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("MIGRATING", ))
		return ErrInvalidNotification
	}

	if .Conn == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("MIGRATING"))
		return ErrInvalidNotification
	}

	,  := .Conn.(*pool.Conn)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("MIGRATING", .Conn, ))
		return ErrInvalidNotification
	}

	// Apply relaxed timeout to this specific connection
	if internal.LogLevel.InfoOrAbove() {
		internal.Logger.Printf(, "%s", logs.RelaxedTimeoutDueToNotification(.GetID(), "MIGRATING", .manager.config.RelaxedTimeout))
	}
	.SetRelaxedTimeout(.manager.config.RelaxedTimeout, .manager.config.RelaxedTimeout)

	// Record relaxed timeout metric
	if  := pool.GetMetricConnectionRelaxedTimeoutCallback();  != nil {
		(, 1, , PoolNameMain, "MIGRATING")
	}

	return nil
}

// handleMigrated processes MIGRATED notifications.
// MIGRATED indicates that a connection migration has completed.
// This is a per-connection notification that clears relaxed timeouts.
// Expected format: ["MIGRATED", ...]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 2 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("MIGRATED", ))
		return ErrInvalidNotification
	}

	if .Conn == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("MIGRATED"))
		return ErrInvalidNotification
	}

	,  := .Conn.(*pool.Conn)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("MIGRATED", .Conn, ))
		return ErrInvalidNotification
	}

	// Clear relaxed timeout for this specific connection
	if internal.LogLevel.InfoOrAbove() {
		 := .GetID()
		internal.Logger.Printf(, "%s", logs.UnrelaxedTimeout())
	}
	.ClearRelaxedTimeout()
	return nil
}

// handleFailingOver processes FAILING_OVER notifications.
// FAILING_OVER indicates that a failover is starting.
// This is a per-connection notification that applies relaxed timeouts.
// Expected format: ["FAILING_OVER", ...]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 2 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("FAILING_OVER", ))
		return ErrInvalidNotification
	}

	if .Conn == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("FAILING_OVER"))
		return ErrInvalidNotification
	}

	,  := .Conn.(*pool.Conn)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("FAILING_OVER", .Conn, ))
		return ErrInvalidNotification
	}

	// Apply relaxed timeout to this specific connection
	if internal.LogLevel.InfoOrAbove() {
		 := .GetID()
		internal.Logger.Printf(, "%s", logs.RelaxedTimeoutDueToNotification(, "FAILING_OVER", .manager.config.RelaxedTimeout))
	}
	.SetRelaxedTimeout(.manager.config.RelaxedTimeout, .manager.config.RelaxedTimeout)

	// Record relaxed timeout metric
	if  := pool.GetMetricConnectionRelaxedTimeoutCallback();  != nil {
		(, 1, , PoolNameMain, "FAILING_OVER")
	}

	return nil
}

// handleFailedOver processes FAILED_OVER notifications.
// FAILED_OVER indicates that a failover has completed.
// This is a per-connection notification that clears relaxed timeouts.
// Expected format: ["FAILED_OVER", ...]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 2 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("FAILED_OVER", ))
		return ErrInvalidNotification
	}

	if .Conn == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("FAILED_OVER"))
		return ErrInvalidNotification
	}

	,  := .Conn.(*pool.Conn)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("FAILED_OVER", .Conn, ))
		return ErrInvalidNotification
	}

	// Clear relaxed timeout for this specific connection
	if internal.LogLevel.InfoOrAbove() {
		 := .GetID()
		internal.Logger.Printf(, "%s", logs.UnrelaxedTimeout())
	}
	.ClearRelaxedTimeout()
	return nil
}

// handleSMigrating processes SMIGRATING notifications.
// SMIGRATING indicates that a cluster slot is in the process of migrating to a different node.
// This is a per-connection notification that applies relaxed timeouts during slot migration.
// Expected format: ["SMIGRATING", SeqID, slot/range1-range2, ...]
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	if len() < 3 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATING", ))
		return ErrInvalidNotification
	}

	// Validate SeqID (position 1)
	if ,  := [1].(int64); ! {
		internal.Logger.Printf(, "%s", logs.InvalidSeqIDInSMigratingNotification([1]))
		return ErrInvalidNotification
	}

	if .Conn == nil {
		internal.Logger.Printf(, "%s", logs.NoConnectionInHandlerContext("SMIGRATING"))
		return ErrInvalidNotification
	}

	,  := .Conn.(*pool.Conn)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidConnectionTypeInHandlerContext("SMIGRATING", .Conn, ))
		return ErrInvalidNotification
	}

	// Apply relaxed timeout to this specific connection
	if internal.LogLevel.InfoOrAbove() {
		internal.Logger.Printf(, "%s", logs.RelaxedTimeoutDueToNotification(.GetID(), "SMIGRATING", .manager.config.RelaxedTimeout))
	}
	.SetRelaxedTimeout(.manager.config.RelaxedTimeout, .manager.config.RelaxedTimeout)
	return nil
}

// handleSMigrated processes SMIGRATED notifications.
// SMIGRATED indicates that a cluster slot has finished migrating to a different node.
// This is a cluster-level notification that triggers cluster state reload.
//
// Expected RESP3 format:
//
//	>3
//	+SMIGRATED
//	:SeqID
//	*<num_entries>       <- array of triplet arrays
//	  *3                 <- each triplet is a 3-element array
//	    +<source>        <- node from which slots are migrating FROM
//	    +<destination>   <- node to which slots are migrating TO
//	    +<slots>         <- comma-separated slots and/or ranges (e.g., "123,789-1000")
//
// A source and target endpoint may appear in multiple triplets.
// The notification is only processed if the connection's NodeAddress matches one of the source endpoints.
//
// Note: Multiple connections may receive the same notification, so we deduplicate by SeqID before triggering reload.
// but we still process the notification on each connection to clear the relaxed timeout.
// In the case when the connection is from MOVED/ASK, the connection's original endpoint is not set,
// so we will not be able to match the source endpoint. In such case, we will trigger the reload callback with the first target endpoint.
func ( *NotificationHandler) ( context.Context,  push.NotificationHandlerContext,  []interface{}) error {
	// Expected: ["SMIGRATED", SeqID, [[source, target, slots], ...]]
	// Minimum 3 elements: SMIGRATED, SeqID, and the array of triplets
	if len() < 3 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED", ))
		return ErrInvalidNotification
	}

	// Extract SeqID (position 1)
	,  := [1].(int64)
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidSeqIDInSMigratedNotification([1]))
		return ErrInvalidNotification
	}

	// Extract the array of triplets (position 2)
	,  := [2].([]interface{})
	if ! {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (triplets array)", [2]))
		return ErrInvalidNotification
	}

	if len() == 0 {
		internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (empty triplets)", ))
		return ErrInvalidNotification
	}

	// Get the connection's endpoints to check if this notification is relevant
	// We check against both nodeAddress (from CLUSTER SLOTS) and addr (after resolution)
	// since we cannot be certain which format the notification source will use
	var  string
	var  string
	if .manager.options != nil {
		 = .manager.options.GetNodeAddress()
		 = .manager.options.GetAddr()
	}

	// Helper function to check if source matches either of our endpoints
	// notification source can be either the node address or the addr after resolution
	 := func( string) bool {
		if  ==  {
			return true
		}
		if  ==  {
			return true
		}
		return false
	}

	// Parse triplets and check if any source matches our connection's endpoints
	var  []struct {
		 string
		 string
		  string
	}
	var  []string

	for ,  := range  {
		// Each triplet should be a 3-element array: [source, target, slots]
		,  := .([]interface{})
		if ! || len() != 3 {
			internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (triplet format)", ))
			continue
		}

		// Extract source endpoint
		,  := [0].(string)
		if ! {
			internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (source)", [0]))
			continue
		}

		// Extract target endpoint
		,  := [1].(string)
		if ! {
			internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (target)", [1]))
			continue
		}

		// Extract slots
		,  := [2].(string)
		if ! {
			internal.Logger.Printf(, "%s", logs.InvalidNotification("SMIGRATED (slots)", [2]))
			continue
		}

		// Check if this triplet's source matches our connection's endpoints
		if () {
			 = append(, struct {
				 string
				 string
				  string
			}{, , })
			 := strings.Split(, ",")
			 = append(, ...)
		}
	}

	var  uint64
	// Reset relaxed timeout for this specific connection
	if .Conn != nil {
		,  := .Conn.(*pool.Conn)
		if  {
			if internal.LogLevel.InfoOrAbove() {
				 = .GetID()
				internal.Logger.Printf(, "%s", logs.UnrelaxedTimeout())
			}
			.ClearRelaxedTimeout()
		}
	}

	// If no matching triplets, this notification is not relevant to this connection
	if len() == 0 {
		return nil
	}

	// Deduplicate by SeqID - multiple connections may receive the same notification
	// Only trigger cluster state reload once per seqID
	if .manager.MarkSMigratedSeqIDProcessed() {
		// Use the first matching triplet
		 := [0].
		 := 

		if internal.LogLevel.InfoOrAbove() {
			internal.Logger.Printf(, "%s", logs.TriggeringClusterStateReload(, , ))
		}

		// Trigger cluster state reload via callback
		.manager.TriggerClusterStateReload(, , )
	}

	return nil
}