package config

import (
	"fmt"

	"github.com/alexei/tinyforge/internal/store"
	"gopkg.in/yaml.v3"
)

// ExportConfig reads the current database state and produces a SeedConfig YAML
// representation. Credential fields (tokens, passwords) are exported as
// placeholder strings since they are encrypted in the database. After the hard
// cutover, only global settings + registries are exported — workloads and
// triggers are created through the API, not via seed files.
func ExportConfig(db *store.Store) ([]byte, error) {
	cfg, err := buildSeedConfig(db)
	if err != nil {
		return nil, fmt.Errorf("build seed config: %w", err)
	}

	data, err := yaml.Marshal(cfg)
	if err != nil {
		return nil, fmt.Errorf("marshal yaml: %w", err)
	}

	return data, nil
}

func buildSeedConfig(db *store.Store) (SeedConfig, error) {
	settings, err := db.GetSettings()
	if err != nil {
		return SeedConfig{}, fmt.Errorf("get settings: %w", err)
	}

	registries, err := db.GetAllRegistries()
	if err != nil {
		return SeedConfig{}, fmt.Errorf("get registries: %w", err)
	}

	cfg := SeedConfig{
		Global: GlobalConfig{
			Domain:           settings.Domain,
			ServerIP:         settings.ServerIP,
			Network:          settings.Network,
			SubdomainPattern: settings.SubdomainPattern,
			NotificationURL:  settings.NotificationURL,
			Npm: NpmConfig{
				URL:      settings.NpmURL,
				Email:    settings.NpmEmail,
				Password: "CHANGE_ME", // Encrypted value, export placeholder.
			},
		},
		Registries: make(map[string]RegistryDef),
	}

	for _, reg := range registries {
		cfg.Registries[reg.Name] = RegistryDef{
			URL:   reg.URL,
			Type:  reg.Type,
			Token: "CHANGE_ME", // Encrypted value, export placeholder.
		}
	}

	return cfg, nil
}
