package httpcache

import (
	"crypto/sha256"
	"encoding/hex"
	"strings"
)

// Checksum returns a stable hex-encoded SHA-256 checksum for the given parts.
func Checksum(parts ...string) string {
	h := sha256.New()
	for _, part := range parts {
		_, _ = h.Write([]byte(part))
		_, _ = h.Write([]byte{0})
	}
	return hex.EncodeToString(h.Sum(nil))
}

// IfNoneMatchMatches reports whether an If-None-Match header matches the provided ETag.
//
// This supports both quoted and unquoted ETags, as well as comma-separated lists.
func IfNoneMatchMatches(ifNoneMatchHeader string, etag string) bool {
	if etag == "" {
		return false
	}
	header := strings.TrimSpace(ifNoneMatchHeader)
	if header == "" {
		return false
	}
	for _, token := range strings.Split(header, ",") {
		candidate := strings.TrimSpace(token)
		candidate = strings.TrimPrefix(candidate, "W/")
		candidate = strings.Trim(candidate, "\"")
		if candidate == etag {
			return true
		}
	}
	return false
}
