package utils

import (
	"fmt"
	"strings"
)

// ParseETag extracts the ETag value from HTTP ETag header
// Handles both strong ETags ("123") and weak ETags (W/"123")
func ParseETag(etag string) string {
	if etag == "" {
		return ""
	}

	// Remove W/ prefix for weak ETags
	if strings.HasPrefix(etag, "W/") {
		etag = etag[2:]
	}

	// Remove surrounding quotes
	if len(etag) >= 2 && strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
		etag = etag[1 : len(etag)-1]
	}

	return etag
}

// FormatETag formats a version ID into a proper HTTP ETag header value
func FormatETag(versionId string, weak bool) string {
	if versionId == "" {
		return ""
	}

	if weak {
		return fmt.Sprintf(`W/"%s"`, versionId)
	}

	return fmt.Sprintf(`"%s"`, versionId)
}

// IsValidETag validates if the given string is a valid ETag format
func IsValidETag(etag string) bool {
	if etag == "" {
		return false
	}

	// Check for weak ETag format
	if strings.HasPrefix(etag, "W/") {
		etag = etag[2:]
	}

	// Must be quoted
	return len(etag) >= 2 && strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"")
}
