// Package crd implements CRD installation, CR seeding, and secrets management
// for the selected host cluster. CRDs are dumped from the staging cluster
// as part of the active lifecycle, not through a standalone user command.
package crd

import (
	"fmt"
	"strings"
)

// ServiceResult holds the outcome for one service's CRD installation.
type ServiceResult struct {
	Service  string `json:"service"`
	Status   string `json:"status"` // "ok", "skipped", "failed", "cached"
	CRDCount int    `json:"crd_count"`
	CRCount  int    `json:"cr_count,omitempty"`
	Error    string `json:"error,omitempty"`
}

// SecretResult holds the outcome for one service's secret injection.
type SecretResult struct {
	Service  string `json:"service"`
	Status   string `json:"status"` // "ok", "failed"
	KeyCount int    `json:"key_count"`
	Error    string `json:"error,omitempty"`
}

// Result holds the outcome of a CRD installation + secrets run.
type Result struct {
	Services []ServiceResult `json:"services"`
	Secrets  []SecretResult  `json:"secrets,omitempty"`
}

// FormatText implements model.TextFormatter for human-readable output.
func (r *Result) FormatText() string {
	var b strings.Builder
	b.WriteString("CRD install\n\n")

	if len(r.Services) > 0 {
		b.WriteString("  CRDs:\n")
		for _, svc := range r.Services {
			switch svc.Status {
			case "ok":
				fmt.Fprintf(&b, "    [ok]     %-30s %d CRD(s)", svc.Service, svc.CRDCount)
				if svc.CRCount > 0 {
					fmt.Fprintf(&b, ", %d CR(s) seeded", svc.CRCount)
				}
				b.WriteString("\n")
			case "cached":
				fmt.Fprintf(&b, "    [cached] %-30s %d CRD(s)\n", svc.Service, svc.CRDCount)
			case "skipped":
				fmt.Fprintf(&b, "    [skip]   %s\n", svc.Service)
			case "failed":
				fmt.Fprintf(&b, "    [FAIL]   %s: %s\n", svc.Service, svc.Error)
			}
		}
	}

	if len(r.Secrets) > 0 {
		b.WriteString("\n  Secrets:\n")
		for _, sec := range r.Secrets {
			switch sec.Status {
			case "ok":
				fmt.Fprintf(&b, "    [ok]     %-30s %d key(s)\n", sec.Service, sec.KeyCount)
			case "failed":
				fmt.Fprintf(&b, "    [FAIL]   %s: %s\n", sec.Service, sec.Error)
			}
		}
	}

	return b.String()
}
