package packs

import (
	"context"
	"fmt"
	"strings"
)

// FinalizeStoppedSourceSetConnectorIncarnationTransition retires connector
// runtime rows owned by the generation that is being replaced. It must run in
// the same transaction that selects the prepared generation: candidate apply
// is deliberately forbidden from changing the still-active incarnation.
func FinalizeStoppedSourceSetConnectorIncarnationTransition(
	ctx context.Context,
	tx sqlExecer,
	packName string,
	previousPackInstallID string,
	candidatePackInstallID string,
) error {
	packName = strings.TrimSpace(packName)
	previousPackInstallID = strings.TrimSpace(previousPackInstallID)
	candidatePackInstallID = strings.TrimSpace(candidatePackInstallID)
	if ctx == nil || tx == nil || packName == "" || previousPackInstallID == "" ||
		candidatePackInstallID == "" || previousPackInstallID == candidatePackInstallID {
		return fmt.Errorf("stopped connector incarnation transition requires distinct canonical pack identities")
	}

	// Old routes cannot accept new traffic after selection changes. Rows needed
	// by queued work remain readable by their immutable version coordinate.
	if _, err := tx.ExecContext(ctx, `
UPDATE _System_ConnectorInboundRoute
   SET IsCurrent = 0, LastModifiedDate = NOW()
 WHERE Namespace = ?
   AND InstalledPackId = ?
   AND COALESCE(IsDeleted, 0) = 0
   AND COALESCE(IsCurrent, 0) = 1`, packName, previousPackInstallID); err != nil {
		return fmt.Errorf("demote previous connector route incarnation for pack %s: %w", packName, err)
	}
	if _, err := tx.ExecContext(ctx, `
UPDATE _System_ConnectorInboundRoute
   SET IsDeleted = 1, IsCurrent = 0, LastModifiedDate = NOW()
 WHERE Namespace = ?
   AND InstalledPackId = ?
   AND COALESCE(IsDeleted, 0) = 0
   AND NOT EXISTS (
       SELECT 1
         FROM _System_ConnectorEvent e
        WHERE e.InstalledPackId = _System_ConnectorInboundRoute.InstalledPackId
          AND LOWER(TRIM(e.EventKind)) = _System_ConnectorInboundRoute.EventKind
          AND (e.RouteVersion = _System_ConnectorInboundRoute.Version OR e.RouteVersion IS NULL)
          AND e.Status IN ('pending', 'processing', 'failed')
   )`, packName, previousPackInstallID); err != nil {
		return fmt.Errorf("retire previous connector route incarnation for pack %s: %w", packName, err)
	}
	if _, err := tx.ExecContext(ctx, `
UPDATE _System_ConnectorInboundHandlerConfig
   SET IsDeleted = 1, LastModifiedDate = NOW()
 WHERE Namespace = ?
   AND InstalledPackId = ?
   AND COALESCE(IsDeleted, 0) = 0`, packName, previousPackInstallID); err != nil {
		return fmt.Errorf("retire previous connector handler-config incarnation for pack %s: %w", packName, err)
	}
	if _, err := tx.ExecContext(ctx, `
UPDATE _System_ConnectorCalloutProfile
   SET IsDeleted = 1, LastModifiedDate = NOW()
 WHERE OwnerPack = ?
   AND InstalledPackId = ?
   AND COALESCE(IsDeleted, 0) = 0`, packName, previousPackInstallID); err != nil {
		return fmt.Errorf("retire previous connector callout-profile incarnation for pack %s: %w", packName, err)
	}
	return nil
}
