package auth

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

const APIKeyPrefix = "prism_"

func GenerateAPIKey() (string, error) {
	var b [16]byte
	if _, err := rand.Read(b[:]); err != nil {
		return "", err
	}
	return APIKeyPrefix + hex.EncodeToString(b[:]), nil
}

func HashAPIKey(key string) string {
	sum := sha256.Sum256([]byte(key))
	return hex.EncodeToString(sum[:])
}

func APIKeyDisplayPrefix(key string) string {
	key = strings.TrimSpace(key)
	if len(key) <= 12 {
		return key
	}
	return key[:12] + "…"
}

func IsAPIKeyFormat(key string) bool {
	return strings.HasPrefix(strings.TrimSpace(key), APIKeyPrefix)
}

func ValidateAPIKeyFormat(key string) error {
	key = strings.TrimSpace(key)
	if !strings.HasPrefix(key, APIKeyPrefix) {
		return fmt.Errorf("invalid api key format")
	}
	raw := strings.TrimPrefix(key, APIKeyPrefix)
	if len(raw) != 32 {
		return fmt.Errorf("invalid api key length")
	}
	if _, err := hex.DecodeString(raw); err != nil {
		return fmt.Errorf("invalid api key encoding")
	}
	return nil
}
