package jwt

import (
	"github.com/rwadurian/mpc-system/pkg/jwt"
	"github.com/rwadurian/mpc-system/services/account/application/ports"
)

// TokenServiceAdapter implements TokenService using JWT
type TokenServiceAdapter struct {
	jwtService *jwt.JWTService
}

// NewTokenServiceAdapter creates a new TokenServiceAdapter
func NewTokenServiceAdapter(jwtService *jwt.JWTService) ports.TokenService {
	return &TokenServiceAdapter{jwtService: jwtService}
}

// GenerateAccessToken generates an access token for an account
func (t *TokenServiceAdapter) GenerateAccessToken(accountID, username string) (string, error) {
	return t.jwtService.GenerateAccessToken(accountID, username)
}

// GenerateRefreshToken generates a refresh token for an account
func (t *TokenServiceAdapter) GenerateRefreshToken(accountID string) (string, error) {
	return t.jwtService.GenerateRefreshToken(accountID)
}

// ValidateAccessToken validates an access token
func (t *TokenServiceAdapter) ValidateAccessToken(token string) (claims map[string]interface{}, err error) {
	accessClaims, err := t.jwtService.ValidateAccessToken(token)
	if err != nil {
		return nil, err
	}

	return map[string]interface{}{
		"subject":  accessClaims.Subject,
		"username": accessClaims.Username,
		"issuer":   accessClaims.Issuer,
	}, nil
}

// ValidateRefreshToken validates a refresh token
func (t *TokenServiceAdapter) ValidateRefreshToken(token string) (accountID string, err error) {
	claims, err := t.jwtService.ValidateRefreshToken(token)
	if err != nil {
		return "", err
	}
	return claims.Subject, nil
}

// RefreshAccessToken refreshes an access token using a refresh token
func (t *TokenServiceAdapter) RefreshAccessToken(refreshToken string) (accessToken string, err error) {
	return t.jwtService.RefreshAccessToken(refreshToken)
}
