// Package system contains data-layer implementations for system runtime
// settings, authentication tokens, and bootstrap definitions.
package system

import (
	"errors"
	"kra/internal/biz/system"
	"time"

	"kra/internal/conf"
	"kra/internal/security"

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

type runtimeSettings struct{ runtime *conf.Runtime }

func NewRuntimeSettings(runtime *conf.Runtime) system.RuntimeSettings {
	return &runtimeSettings{runtime: runtime}
}

func (s *runtimeSettings) RouterPrefix() string {
	config := s.runtime.Admin()
	if config == nil {
		return ""
	}
	return config.RouterPrefix
}

func (s *runtimeSettings) JWTSettings() system.JWTSettings {
	value := system.JWTSettings{Issuer: "kra", Expires: 7 * 24 * time.Hour, Buffer: 24 * time.Hour}
	config := s.runtime.Admin()
	if config == nil || config.Jwt == nil {
		return value
	}
	value.SigningKey = config.Jwt.SigningKey
	if config.Jwt.Issuer != "" {
		value.Issuer = config.Jwt.Issuer
	}
	if config.Jwt.ExpiresTime != nil {
		value.Expires = config.Jwt.ExpiresTime.AsDuration()
	}
	if config.Jwt.BufferTime != nil {
		value.Buffer = config.Jwt.BufferTime.AsDuration()
	}
	return value
}

func (s *runtimeSettings) CaptchaSettings() system.CaptchaSettings {
	value := system.CaptchaSettings{KeyLong: 6, ImageWidth: 240, ImageHeight: 80, StoreExpiration: 3 * time.Minute}
	config := s.runtime.Admin()
	if config == nil || config.Captcha == nil {
		return value
	}
	if config.Captcha.KeyLong > 0 {
		value.KeyLong = int(config.Captcha.KeyLong)
	}
	if config.Captcha.ImgWidth > 0 {
		value.ImageWidth = int(config.Captcha.ImgWidth)
	}
	if config.Captcha.ImgHeight > 0 {
		value.ImageHeight = int(config.Captcha.ImgHeight)
	}
	if config.Captcha.StoreExpiration != nil {
		value.StoreExpiration = config.Captcha.StoreExpiration.AsDuration()
	}
	return value
}

func (s *runtimeSettings) MediaSettings() system.MediaSettings {
	config := s.runtime.Admin()
	if config == nil || config.Media == nil {
		return system.MediaSettings{}
	}
	return system.MediaSettings{SessionTTL: int(config.Media.SessionTtl), MaxFileSize: config.Media.MaxFileSize, ChunkDir: config.Media.ChunkDir}
}

func (s *runtimeSettings) UseMultipoint() bool {
	config := s.runtime.Admin()
	return config != nil && config.System != nil && config.System.UseMultipoint
}

type tokenIssuer struct{ settings system.RuntimeSettings }

func NewTokenIssuer(settings system.RuntimeSettings) system.TokenIssuer {
	return &tokenIssuer{settings: settings}
}

func (i *tokenIssuer) IssueToken(user *system.User, authorityID uint, mustChangePassword bool, expires time.Duration) (*system.IssuedToken, error) {
	settings := i.settings.JWTSettings()
	if expires <= 0 {
		expires = settings.Expires
	}
	passwordVersion := int64(0)
	if user.PasswordUpdatedAt != nil {
		passwordVersion = user.PasswordUpdatedAt.UnixNano()
	}
	token, claims, err := security.Generate(settings.SigningKey, settings.Issuer, expires, settings.Buffer, user.ID, authorityID, user.UUID, user.Username, user.NickName, mustChangePassword, passwordVersion)
	if err != nil {
		return nil, err
	}
	return &system.IssuedToken{Value: token, ExpiresAt: claims.ExpiresAt.Time, TTL: expires}, nil
}

func (i *tokenIssuer) ReissueToken(source *system.AuthClaims, authorityID uint) (*system.IssuedToken, error) {
	if source == nil {
		return nil, errors.New("nil JWT claims")
	}
	settings := i.settings.JWTSettings()
	claims := &security.Claims{
		UUID: source.UUID, ID: source.ID, Username: source.Username, NickName: source.NickName,
		AuthorityID: authorityID, BufferTime: int64(source.BufferTime / time.Second), UserType: source.UserType,
		MustChangePwd: source.MustChangePwd, PasswordVersion: source.PasswordVersion,
		RegisteredClaims: jwt.RegisteredClaims{
			Audience: jwt.ClaimStrings{security.TokenAudience}, Issuer: settings.Issuer,
			IssuedAt: jwt.NewNumericDate(source.IssuedAt), NotBefore: jwt.NewNumericDate(source.NotBefore), ExpiresAt: jwt.NewNumericDate(source.ExpiresAt),
		},
	}
	token, err := security.Sign(settings.SigningKey, claims)
	if err != nil {
		return nil, err
	}
	return &system.IssuedToken{Value: token, ExpiresAt: source.ExpiresAt, TTL: time.Until(source.ExpiresAt)}, nil
}

func (i *tokenIssuer) ParseToken(token string) (*system.AuthClaims, error) {
	settings := i.settings.JWTSettings()
	claims, err := security.ParseWithIssuer(token, settings.SigningKey, settings.Issuer)
	if err != nil {
		switch {
		case errors.Is(err, security.ErrTokenExpired):
			return nil, system.ErrTokenExpired
		case errors.Is(err, security.ErrTokenMalformed):
			return nil, system.ErrTokenMalformed
		case errors.Is(err, security.ErrTokenSignatureInvalid):
			return nil, system.ErrTokenSignatureInvalid
		case errors.Is(err, security.ErrTokenNotValidYet):
			return nil, system.ErrTokenNotValidYet
		default:
			return nil, system.ErrTokenInvalid
		}
	}
	audience := append([]string(nil), claims.Audience...)
	issuedAt := time.Time{}
	if claims.IssuedAt != nil {
		issuedAt = claims.IssuedAt.Time
	}
	notBefore, expiresAt := time.Time{}, time.Time{}
	if claims.NotBefore != nil {
		notBefore = claims.NotBefore.Time
	}
	if claims.ExpiresAt != nil {
		expiresAt = claims.ExpiresAt.Time
	}
	return &system.AuthClaims{UUID: claims.UUID, ID: claims.ID, Username: claims.Username, NickName: claims.NickName, AuthorityID: claims.AuthorityID, UserType: claims.UserType, BufferTime: time.Duration(claims.BufferTime) * time.Second, MustChangePwd: claims.MustChangePwd, PasswordVersion: claims.PasswordVersion, Issuer: claims.Issuer, Audience: audience, IssuedAt: issuedAt, NotBefore: notBefore, ExpiresAt: expiresAt}, nil
}
