// Package config loads and exports seed configuration. After the hard
// cutover the seed shape covers only what survives the workload-first
// refactor: global settings and registries. Project / stage / volume
// seeding is gone; the new way to bootstrap a workload is the plugin
// pipeline (POST /api/workloads).
package config

import (
	"fmt"
	"log/slog"
	"os"

	"github.com/alexei/tinyforge/internal/crypto"
	"github.com/alexei/tinyforge/internal/store"
	"github.com/google/uuid"
)

// ImportSeed loads the seed YAML file and imports its contents into the store.
// Import is idempotent: it is skipped if any registries already exist.
// Credential fields (registry tokens, NPM password) are encrypted before storage.
func ImportSeed(db *store.Store, seedPath string) error {
	if _, err := os.Stat(seedPath); os.IsNotExist(err) {
		slog.Info("no seed file, skipping import", "path", seedPath)
		return nil
	}

	populated, err := isPopulated(db)
	if err != nil {
		return fmt.Errorf("check if db is populated: %w", err)
	}
	if populated {
		slog.Info("database already has data, skipping seed import")
		return nil
	}

	cfg, err := LoadSeedFile(seedPath)
	if err != nil {
		return fmt.Errorf("load seed file: %w", err)
	}

	encKey, err := crypto.KeyFromEnv()
	if err != nil {
		return fmt.Errorf("encryption key: %w", err)
	}

	if err := importAll(db, cfg, encKey); err != nil {
		return fmt.Errorf("import seed: %w", err)
	}

	slog.Info("seed config imported", "path", seedPath)
	return nil
}

// isPopulated returns true if the store already contains any registries.
// Workloads / apps are intentionally not consulted — they get created
// through the API, not seeded.
func isPopulated(db *store.Store) (bool, error) {
	registries, err := db.GetAllRegistries()
	if err != nil {
		return false, fmt.Errorf("get registries: %w", err)
	}
	return len(registries) > 0, nil
}

// importAll runs the seed import inside a database transaction.
func importAll(db *store.Store, cfg SeedConfig, encKey [32]byte) error {
	tx, err := db.DB().Begin()
	if err != nil {
		return fmt.Errorf("begin transaction: %w", err)
	}
	defer tx.Rollback() //nolint:errcheck // rollback after commit is a no-op

	timestamp := store.Now()

	for name, regDef := range cfg.Registries {
		encToken, err := crypto.EncryptIfNotEmpty(encKey, regDef.Token)
		if err != nil {
			return fmt.Errorf("encrypt registry %q token: %w", name, err)
		}

		id := uuid.New().String()
		_, err = tx.Exec(
			`INSERT INTO registries (id, name, url, type, token, created_at, updated_at)
			 VALUES (?, ?, ?, ?, ?, ?, ?)`,
			id, name, regDef.URL, regDef.Type, encToken, timestamp, timestamp,
		)
		if err != nil {
			return fmt.Errorf("insert registry %q: %w", name, err)
		}
	}

	encNpmPassword, err := crypto.EncryptIfNotEmpty(encKey, cfg.Global.Npm.Password)
	if err != nil {
		return fmt.Errorf("encrypt npm password: %w", err)
	}

	subdomainPattern := cfg.Global.SubdomainPattern
	if subdomainPattern == "" {
		subdomainPattern = "stage-{stage}-{project}"
	}

	_, err = tx.Exec(
		`UPDATE settings SET
			domain=?, server_ip=?, network=?, subdomain_pattern=?, notification_url=?,
			npm_url=?, npm_email=?, npm_password=?, updated_at=?
		 WHERE id = 1`,
		cfg.Global.Domain, cfg.Global.ServerIP, cfg.Global.Network,
		subdomainPattern, cfg.Global.NotificationURL,
		cfg.Global.Npm.URL, cfg.Global.Npm.Email, encNpmPassword, timestamp,
	)
	if err != nil {
		return fmt.Errorf("update settings: %w", err)
	}

	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit transaction: %w", err)
	}

	return nil
}
