package auth

import (
	"fmt"
	"time"

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

type TokenPair struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
}

type Claims struct {
	Sub            string `json:"sub"`
	Role           string `json:"role"`
	Type           string `json:"type"`
	JTI            string `json:"jti"`
	Exp            int64  `json:"exp"`
	ImpersonatorID *int64 `json:"impersonator_id,omitempty"`
}

type TokenMaker struct {
	secret        []byte
	accessExpiry  time.Duration
	refreshExpiry time.Duration
}

func NewTokenMaker(secret string, accessMinutes int, refreshDays int) *TokenMaker {
	if accessMinutes <= 0 {
		accessMinutes = 30
	}
	if refreshDays <= 0 {
		refreshDays = 7
	}
	return &TokenMaker{
		secret:        []byte(secret),
		accessExpiry:  time.Duration(accessMinutes) * time.Minute,
		refreshExpiry: time.Duration(refreshDays) * 24 * time.Hour,
	}
}

func (m *TokenMaker) Create(subject string, role string, tokenType string) (string, string, error) {
	expiry := m.accessExpiry
	if tokenType == "refresh" {
		expiry = m.refreshExpiry
	}

	signed, jti, _, err := m.create(subject, role, tokenType, expiry, nil)
	return signed, jti, err
}

func (m *TokenMaker) CreateImpersonation(subject string, role string, impersonatorID int64, ttl time.Duration) (string, string, time.Time, error) {
	if ttl <= 0 || ttl > 15*time.Minute {
		ttl = 10 * time.Minute
	}
	return m.create(subject, role, "access", ttl, &impersonatorID)
}

func (m *TokenMaker) create(subject string, role string, tokenType string, expiry time.Duration, impersonatorID *int64) (string, string, time.Time, error) {
	jti := uuid.NewString()
	expiresAt := time.Now().UTC().Add(expiry)
	claims := jwt.MapClaims{
		"sub":  subject,
		"role": role,
		"type": tokenType,
		"exp":  expiresAt.Unix(),
		"jti":  jti,
	}
	if impersonatorID != nil {
		claims["impersonator_id"] = *impersonatorID
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signed, err := token.SignedString(m.secret)
	if err != nil {
		return "", "", time.Time{}, err
	}
	return signed, jti, expiresAt, nil
}

func (m *TokenMaker) Parse(raw string) (*Claims, error) {
	token, err := jwt.Parse(raw, func(token *jwt.Token) (any, error) {
		if token.Method != jwt.SigningMethodHS256 {
			return nil, fmt.Errorf("unexpected signing method: %s", token.Header["alg"])
		}
		return m.secret, nil
	}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
	if err != nil {
		return nil, err
	}
	if !token.Valid {
		return nil, fmt.Errorf("invalid token")
	}

	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		return nil, fmt.Errorf("invalid token claims")
	}

	sub, err := claims.GetSubject()
	if err != nil || sub == "" {
		return nil, fmt.Errorf("invalid token subject")
	}
	exp, err := claims.GetExpirationTime()
	if err != nil || exp == nil {
		return nil, fmt.Errorf("invalid token expiry")
	}

	role, _ := claims["role"].(string)
	tokenType, _ := claims["type"].(string)
	jti, _ := claims["jti"].(string)
	if role == "" || tokenType == "" || jti == "" {
		return nil, fmt.Errorf("invalid token payload")
	}

	var impersonatorID *int64
	if rawID, exists := claims["impersonator_id"]; exists {
		value, ok := numericClaimInt64(rawID)
		if !ok || value <= 0 {
			return nil, fmt.Errorf("invalid impersonator id")
		}
		impersonatorID = &value
	}

	return &Claims{
		Sub:            sub,
		Role:           role,
		Type:           tokenType,
		JTI:            jti,
		Exp:            exp.Unix(),
		ImpersonatorID: impersonatorID,
	}, nil
}

func numericClaimInt64(value any) (int64, bool) {
	switch item := value.(type) {
	case float64:
		parsed := int64(item)
		return parsed, float64(parsed) == item
	case int64:
		return item, true
	case int:
		return int64(item), true
	default:
		return 0, false
	}
}

func (m *TokenMaker) RefreshTTL() time.Duration {
	return m.refreshExpiry
}
