package controlplane

import (
	"context"
	"fmt"
	"log"

	"github.com/pingcap-inc/nexuscrm-controlplane/packs"
	"github.com/nexuscrm/metadata"
	"github.com/nexuscrm/db"
)

func reconcileFlowOrphansBeforeFlowRuntimeMaintenance(ctx context.Context, db *database.TiDBConnection, scope string) error {
	if db == nil {
		return fmt.Errorf("database connection is required for flow runtime maintenance")
	}
	touched, err := packs.ReconcileFlowOrphans(ctx, db)
	if err != nil {
		return fmt.Errorf("reconcile flow orphans before %s flow runtime maintenance: %w", scope, err)
	}
	if touched > 0 {
		log.Printf("%s: auto-reconciled %d orphan FlowDefinition ActiveVersionId row(s) before flow runtime maintenance", scope, touched)
	}
	return nil
}

func runFlowRuntimeMaintenanceAfterOrphanRepair(ctx context.Context, db *database.TiDBConnection, metaSvc *metadata.MetadataService, scope string) error {
	return packs.RunFlowRuntimeMaintenanceAfterOrphanRepair(ctx, db, metaSvc, scope)
}
