// Package config provides secrets management functionality
package config

import (
	"context"
	"fmt"
	"os"
	"strings"
)

// SecretsManager defines the interface for secrets management
type SecretsManager interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, value string) error
	Delete(ctx context.Context, key string) error
	List(ctx context.Context, prefix string) ([]string, error)
}

// EnvSecretsManager retrieves secrets from environment variables
type EnvSecretsManager struct{}

func NewEnvSecretsManager() *EnvSecretsManager { return &EnvSecretsManager{} }

func (e *EnvSecretsManager) Get(ctx context.Context, key string) (string, error) {
	value := os.Getenv(key)
	if value == "" {
		return "", fmt.Errorf("secret %s not found", key)
	}
	return value, nil
}

func (e *EnvSecretsManager) Set(ctx context.Context, key, value string) error {
	return fmt.Errorf("env secrets: Set not supported")
}

func (e *EnvSecretsManager) Delete(ctx context.Context, key string) error {
	return fmt.Errorf("env secrets: Delete not supported")
}

func (e *EnvSecretsManager) List(ctx context.Context, prefix string) ([]string, error) {
	var keys []string
	for _, env := range os.Environ() {
		if strings.HasPrefix(env, prefix) {
			keys = append(keys, strings.SplitN(env, "=", 2)[0])
		}
	}
	return keys, nil
}

// RedactSecret masks a secret for safe logging
func RedactSecret(secret string) string {
	if len(secret) <= 8 {
		return "***"
	}
	return secret[:4] + "..." + secret[len(secret)-4:]
}
