package cache

import (
	"sort"
	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/utils/v2"
	utilsstrings "github.com/gofiber/utils/v2/strings"
)

// Config defines the config for middleware.
type Config struct {
	// Storage is used to store the state of the middleware
	//
	// Default: an in-memory store for this process only
	Storage fiber.Storage

	// Next defines a function to skip this middleware when returned true.
	//
	// Optional. Default: nil
	Next func(c fiber.Ctx) bool

	// CacheInvalidator defines a function to invalidate the cache when returned true
	//
	// Optional. Default: nil
	CacheInvalidator func(fiber.Ctx) bool

	// KeyGenerator allows you to generate custom keys.
	//
	// When nil, the middleware uses a structured key based on:
	//   - Request path (bounded to 192 bytes, hashed if longer)
	//   - Canonical query string (sorted parameters, bounded)
	//   - Selected request headers (from KeyHeaders)
	//   - Selected cookies (from KeyCookies)
	//
	// The resulting cache key is always partitioned by request method internally.
	//
	// Default: nil
	KeyGenerator func(fiber.Ctx) string

	// ExpirationGenerator allows you to generate a custom expiration per request.
	// If nil, the Expiration value is used.
	//
	// Default: nil
	ExpirationGenerator func(fiber.Ctx, *Config) time.Duration

	// CacheHeader header on response header, indicate cache status, with the following possible return value
	//
	// hit, miss, unreachable
	//
	// Optional. Default: X-Cache
	CacheHeader string

	// KeyHeaders is the set of request headers that can change the selected representation and
	// therefore should partition cache entries. Set this to an empty slice to disable
	// header-based partitioning.
	//
	// Header names are normalized to lowercase for case-insensitive matching.
	//
	// Optional. Default: []string{"Accept", "Accept-Encoding", "Accept-Language"}
	KeyHeaders []string

	// KeyCookies is an explicit allow-list of request cookies that should partition cache entries.
	// Cookies are excluded by default to avoid accidental per-user cache fragmentation.
	//
	// Optional. Default: nil
	KeyCookies []string

	// Methods specifies which HTTP methods are eligible for caching.
	// Requests with methods not in this list bypass the cache entirely.
	// Method names are normalized to uppercase automatically.
	// Set to nil to use the default; set to an empty slice to disable caching for all methods.
	//
	// Default: []string{fiber.MethodGet, fiber.MethodHead}
	Methods []string

	// Expiration is the time that a cached response will live
	//
	// Optional. Default: 5 * time.Minute
	Expiration time.Duration

	// Max number of bytes of response bodies simultaneously stored in cache. When limit is reached,
	// entries with the nearest expiration are deleted to make room for new.
	// 0 means no limit
	//
	// Optional. Default: 1 * 1024 * 1024
	MaxBytes uint

	// DisableQueryKeys disables query-string partitioning in cache keys.
	//
	// Optional. Default: false
	DisableQueryKeys bool

	// DisableVaryHeaders disables response Vary-based lookup partitioning.
	//
	// Optional. Default: false
	DisableVaryHeaders bool

	// DisableValueRedaction turns off masking cache keys in logs and error messages when set to true.
	//
	// Optional. Default: false
	DisableValueRedaction bool

	// DisableCacheControl disables client side caching if set to true
	//
	// Optional. Default: false
	DisableCacheControl bool

	// StoreResponseHeaders allows you to store additional headers generated by
	// next middlewares and handlers.
	//
	// Default: false
	StoreResponseHeaders bool
}

// ConfigDefault is the default config
var ConfigDefault = Config{
	Next:                  nil,
	Expiration:            5 * time.Minute,
	CacheHeader:           "X-Cache",
	DisableCacheControl:   false,
	CacheInvalidator:      nil,
	DisableValueRedaction: false,
	KeyGenerator:          nil,
	DisableQueryKeys:      false,
	KeyHeaders:            []string{fiber.HeaderAccept, fiber.HeaderAcceptEncoding, fiber.HeaderAcceptLanguage},
	KeyCookies:            nil,
	Methods:               []string{fiber.MethodGet, fiber.MethodHead},
	DisableVaryHeaders:    false,
	ExpirationGenerator:   nil,
	StoreResponseHeaders:  false,
	Storage:               nil,
	MaxBytes:              1 * 1024 * 1024,
}

// Helper function to set default values
func configDefault(config ...Config) Config {
	// Return default config if nothing provided
	if len(config) < 1 {
		cfg := ConfigDefault
		cfg.KeyHeaders = normalizeHeaderDimensions(cfg.KeyHeaders, ConfigDefault.KeyHeaders)
		cfg.KeyCookies = normalizeCookieDimensions(cfg.KeyCookies, nil)
		if cfg.KeyGenerator == nil {
			cfg.KeyGenerator = func(c fiber.Ctx) string {
				return defaultKeyGenerator(c, &cfg)
			}
		}
		return cfg
	}

	// Override default config
	cfg := config[0]

	// Set default values
	if cfg.Next == nil {
		cfg.Next = ConfigDefault.Next
	}
	if int(cfg.Expiration.Seconds()) == 0 {
		cfg.Expiration = ConfigDefault.Expiration
	}
	if cfg.CacheHeader == "" {
		cfg.CacheHeader = ConfigDefault.CacheHeader
	}
	cfg.KeyHeaders = normalizeHeaderDimensions(cfg.KeyHeaders, ConfigDefault.KeyHeaders)
	cfg.KeyCookies = normalizeCookieDimensions(cfg.KeyCookies, nil)
	// nil = use default methods; explicit empty slice = cache no methods
	if cfg.Methods == nil {
		cfg.Methods = ConfigDefault.Methods
	} else {
		// Normalize method names to uppercase (HTTP methods are case-sensitive
		// and c.Method() returns uppercase, e.g. "GET" not "get").
		// Copy first to avoid mutating the caller's slice.
		normalized := make([]string, len(cfg.Methods))
		for i, m := range cfg.Methods {
			normalized[i] = utilsstrings.ToUpper(m)
		}
		cfg.Methods = normalized
	}
	if cfg.KeyGenerator == nil {
		cfg.KeyGenerator = func(c fiber.Ctx) string {
			return defaultKeyGenerator(c, &cfg)
		}
	}
	return cfg
}

func normalizeHeaderDimensions(values, defaults []string) []string {
	return normalizeKeyDimensions(values, defaults, utilsstrings.ToLower)
}

func normalizeCookieDimensions(values, defaults []string) []string {
	return normalizeKeyDimensions(values, defaults, nil)
}

func normalizeKeyDimensions(values, defaults []string, normalize func(string) string) []string {
	if values == nil {
		if len(defaults) == 0 {
			return nil
		}
		values = defaults
	}

	if len(values) == 0 {
		return nil
	}

	seen := make(map[string]struct{}, len(values))
	out := make([]string, 0, len(values))
	for _, value := range values {
		trimmed := utils.TrimSpace(value)
		if trimmed == "" {
			continue
		}
		normalized := trimmed
		if normalize != nil {
			normalized = normalize(trimmed)
		}
		if _, ok := seen[normalized]; ok {
			continue
		}
		seen[normalized] = struct{}{}
		out = append(out, normalized)
	}

	sort.Strings(out)
	return out
}
