package controlplane

import (
	"fmt"
	"log"
	"time"
)

// JobResult tracks the execution of a control-plane operation.
type JobResult struct {
	Operation string
	Status    string // "completed" | "failed"
	Duration  time.Duration
	Steps     []StepResult
	Error     error
}

// StepResult tracks an individual step within an operation.
type StepResult struct {
	Name     string
	Duration time.Duration
	Error    error
}

// trackStep runs fn, records timing and any error, and appends to the job.
func (j *JobResult) trackStep(name string, fn func() error) {
	start := time.Now()
	err := fn()
	step := StepResult{
		Name:     name,
		Duration: time.Since(start),
		Error:    err,
	}
	j.Steps = append(j.Steps, step)
	if err != nil {
		log.Printf("   ⚠️  %s failed: %v (%.1fs)", name, err, step.Duration.Seconds())
	} else {
		log.Printf("   ✅ %s (%.1fs)", name, step.Duration.Seconds())
	}
}

// Summary returns a human-readable summary of the job.
func (j *JobResult) Summary() string {
	failed := 0
	for _, s := range j.Steps {
		if s.Error != nil {
			failed++
		}
	}
	return fmt.Sprintf("operation=%s status=%s duration=%.1fs steps=%d failed=%d",
		j.Operation, j.Status, j.Duration.Seconds(), len(j.Steps), failed)
}
