// go-server/internal/license/key_provider.go
package license

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

// StaticKeyProvider returns a fixed KeyMaterial from a hex-encoded 32-byte key.
// Used in multi-replica deployments where the key is injected via env var.
type StaticKeyProvider struct {
	material KeyMaterial
}

// NewStaticKeyProvider decodes hexKey (must be 64 hex chars = 32 bytes).
func NewStaticKeyProvider(hexKey string) (*StaticKeyProvider, error) {
	raw, err := hex.DecodeString(hexKey)
	if err != nil {
		return nil, fmt.Errorf("%w: decode hex master key: %v", ErrCredentialKey, err)
	}
	if len(raw) != credentialKeyBytes {
		return nil, fmt.Errorf("%w: hex master key must be %d bytes, got %d",
			ErrCredentialKey, credentialKeyBytes, len(raw))
	}
	digest := sha256.Sum256(raw)
	return &StaticKeyProvider{material: KeyMaterial{
		ID:  "static-" + hex.EncodeToString(digest[:8]),
		Key: append([]byte(nil), raw...),
	}}, nil
}

// LoadOrCreate implements KeyProvider. Never touches the filesystem.
func (p *StaticKeyProvider) LoadOrCreate(_ context.Context) (KeyMaterial, error) {
	return KeyMaterial{
		ID:  p.material.ID,
		Key: append([]byte(nil), p.material.Key...),
	}, nil
}
