package auth

import (
	"errors"
	"os"

	"github.com/golang-jwt/jwt/v5"
)

// package auth

func jwtSecret() ([]byte, error) {
	sec := os.Getenv("JWT_SECRET")
	if len(sec) < 10 {
		return nil, errors.New("JWT_SECRET environment boş veya çok kısa")
	}
	return []byte(sec), nil
}

// ✅ TEK VE DOĞRU TOKEN ÜRETİCİ
func GenerateToken(claims Claims, username string, change bool) (string, error) {
	secret, err := jwtSecret()
	if err != nil {
		return "", err
	}

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

func ValidateToken(tokenStr string) (*Claims, error) {
	secret, err := jwtSecret()
	if err != nil {
		return nil, err
	}

	token, err := jwt.ParseWithClaims(
		tokenStr,
		&Claims{},
		func(token *jwt.Token) (interface{}, error) {
			return secret, nil
		},
	)
	if err != nil {
		return nil, err
	}

	claims, ok := token.Claims.(*Claims)
	if !ok || !token.Valid {
		return nil, errors.New("token geçersiz")
	}
	return claims, nil
}
