package services

import (
	"fmt"
	"os"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
	"veza-backend-api/internal/models"
)

type JWTService struct {
	secretKey []byte
	Config    *models.JWTConfig
}

func NewJWTService(secret string) *JWTService {
	if secret == "" {
		// Fallback to env for safety during transition, or panic if strict
		secret = os.Getenv("JWT_SECRET")
		if secret == "" {
			panic("JWT secret is required")
		}
	}

	// Default config
	config := &models.JWTConfig{
		AccessTokenTTL:  15 * time.Minute,
		RefreshTokenTTL: 30 * 24 * time.Hour,
	}

	return &JWTService{
		secretKey: []byte(secret),
		Config:    config,
	}
}

func (s *JWTService) GenerateAccessToken(user *models.User) (string, error) {
	claims := models.CustomClaims{
		UserID:       user.ID,
		Email:        user.Email,
		Username:     user.Username,
		Role:         user.Role,
		TokenVersion: user.TokenVersion,
		TokenType:    "access",
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(s.Config.AccessTokenTTL)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "veza-api",
			Audience:  jwt.ClaimStrings{"veza-app"},
			ID:        uuid.NewString(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(s.secretKey)
}

func (s *JWTService) GenerateRefreshToken(user *models.User) (string, error) {
	claims := models.CustomClaims{
		UserID:       user.ID,
		TokenVersion: user.TokenVersion,
		IsRefresh:    true, // Mark as refresh token
		TokenType:    "refresh",
		TokenFamily:  uuid.NewString(), // Nouvelle famille de token
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(s.Config.RefreshTokenTTL)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			Issuer:    "veza-api",
			Audience:  jwt.ClaimStrings{"veza-app"},
			ID:        uuid.NewString(),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(s.secretKey)
}

// GenerateTokenPair génère une paire de tokens (access + refresh) en une seule opération
func (s *JWTService) GenerateTokenPair(user *models.User) (*models.TokenPair, error) {
	// Generate access token
	accessToken, err := s.GenerateAccessToken(user)
	if err != nil {
		return nil, fmt.Errorf("failed to generate access token: %w", err)
	}

	// Generate refresh token
	refreshToken, err := s.GenerateRefreshToken(user)
	if err != nil {
		return nil, fmt.Errorf("failed to generate refresh token: %w", err)
	}

	return &models.TokenPair{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
		ExpiresIn:    int(s.Config.AccessTokenTTL.Seconds()),
	}, nil
}

// VerifyToken valide et parse un token JWT
func (s *JWTService) VerifyToken(tokenString string) (*models.CustomClaims, error) {
	return s.ValidateToken(tokenString)
}

// ValidateToken valide un token JWT et retourne les claims
func (s *JWTService) ValidateToken(tokenString string) (*models.CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &models.CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return s.secretKey, nil
	})

	if err != nil {
		return nil, fmt.Errorf("failed to parse token: %w", err)
	}

	if claims, ok := token.Claims.(*models.CustomClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, fmt.Errorf("invalid token")
}

// ParseToken parse un token JWT sans validation complète (utilise ValidateToken)
func (s *JWTService) ParseToken(tokenString string) (*models.CustomClaims, error) {
	return s.ValidateToken(tokenString)
}

// ExtractClaims extrait les claims d'un token JWT
func (s *JWTService) ExtractClaims(tokenString string) (*models.CustomClaims, error) {
	return s.ValidateToken(tokenString)
}

// ExtractUserID extrait l'ID utilisateur depuis un token JWT
// MIGRATION UUID: retourne uuid.UUID au lieu de int64
func (s *JWTService) ExtractUserID(tokenString string) (uuid.UUID, error) {
	claims, err := s.ValidateToken(tokenString)
	if err != nil {
		return uuid.Nil, fmt.Errorf("failed to extract user ID: %w", err)
	}
	return claims.UserID, nil
}

// VerifyTokenVersion vérifie si la version du token correspond à celle de l'utilisateur
func (s *JWTService) VerifyTokenVersion(claims *models.CustomClaims, userTokenVersion int) error {
	if claims.TokenVersion != userTokenVersion {
		return fmt.Errorf("token version mismatch: token version %d does not match user version %d", claims.TokenVersion, userTokenVersion)
	}
	return nil
}
