package migrate

import (
	"context"
	"fmt"

	"github.com/tidbcloud/controlplane9/internal/cluster"
	"github.com/tidbcloud/controlplane9/internal/config"
)

// Step implements cluster.Step for the db_migrate phase.
// It dumps schema from staging and applies it to the local database.
type Step struct {
	// Services is the list of REAL services.
	Services []string
	// StagingDSNs maps service name → staging database DSN.
	StagingDSNs map[string]string
	// LocalDSNs maps service name → local database DSN.
	LocalDSNs map[string]string
	// AdminDSN is the local admin DSN for DROP/CREATE operations.
	AdminDSN string
	// SeedConfig from cp9.yaml.
	SeedConfig config.SeedConfig
	// StateDir for dump caching.
	StateDir string
}

func (s *Step) Name() cluster.StepName { return cluster.StepDBMigrate }

func (s *Step) Run(ctx context.Context) error {
	if len(s.Services) == 0 {
		return nil
	}

	result := Run(ctx, &Options{
		Services:    s.Services,
		StagingDSNs: s.StagingDSNs,
		LocalDSNs:   s.LocalDSNs,
		AdminDSN:    s.AdminDSN,
		SeedConfig:  s.SeedConfig,
		StateDir:    s.StateDir,
	})

	for _, svc := range result.Services {
		if svc.Status == "failed" {
			return fmt.Errorf("migration failed for %s: %s", svc.Service, svc.Error)
		}
	}

	return nil
}
