package auth

import (
	"fmt"
	"os"

	"github.com/acp/interceptor/internal/config"
)

// ValidatorFromConfig builds a JWT validator from interceptor configuration.
func ValidatorFromConfig(cfg config.Config) (*Validator, error) {
	jwtCfg := JWTConfig{
		Enabled:  cfg.JWTEnabled,
		Required: cfg.JWTRequired,
		Issuer:   cfg.JWTIssuer,
		Audience: cfg.JWTAudience,
	}
	if !cfg.JWTEnabled {
		return NewValidator(jwtCfg)
	}

	var pem []byte
	switch {
	case cfg.JWTPublicKeyPEM != "":
		pem = []byte(cfg.JWTPublicKeyPEM)
	case cfg.JWTPublicKeyPath != "":
		b, err := os.ReadFile(cfg.JWTPublicKeyPath)
		if err != nil {
			return nil, fmt.Errorf("read JWT public key: %w", err)
		}
		pem = b
	default:
		return nil, fmt.Errorf("JWT_ENABLED requires JWT_PUBLIC_KEY_PATH or JWT_PUBLIC_KEY_PEM")
	}

	pub, err := LoadPublicKeyFromPEM(pem)
	if err != nil {
		return nil, fmt.Errorf("parse JWT public key: %w", err)
	}
	jwtCfg.PublicKey = pub
	return NewValidator(jwtCfg)
}
