package config

import (
	"backend/pkg/permission/domain/token"
)

// Config represents the configuration for the permission module
type Config struct {
	Token TokenConfig `json:"token" yaml:"token"`
	// RBAC 配置
	RBAC RBACConfig
	// Role 角色配置
	Role RoleConfig
}

// TokenConfig represents token configuration
type TokenConfig struct {
	// JWT signing configuration
	Secret string `json:"secret" yaml:"secret"`

	// Token expiration settings
	Expired        ExpiredConfig `json:"expired" yaml:"expired"`
	RefreshExpires ExpiredConfig `json:"refresh_expires" yaml:"refresh_expires"`

	// Issuer information
	Issuer string `json:"issuer" yaml:"issuer"`

	// Token limits
	MaxTokensPerUser   int `json:"max_tokens_per_user" yaml:"max_tokens_per_user"`
	MaxTokensPerDevice int `json:"max_tokens_per_device" yaml:"max_tokens_per_device"`

	// Security settings
	EnableDeviceTracking bool `json:"enable_device_tracking" yaml:"enable_device_tracking"`
}

// ExpiredConfig represents expiration configuration
type ExpiredConfig struct {
	Seconds int64 `json:"seconds" yaml:"seconds"`
}

// Validate validates the token configuration
func (c *TokenConfig) Validate() error {
	if c.Secret == "" {
		return ErrMissingSecret
	}

	if c.Expired.Seconds <= 0 {
		c.Expired.Seconds = token.DefaultAccessTokenExpiry
	}

	if c.RefreshExpires.Seconds <= 0 {
		c.RefreshExpires.Seconds = token.DefaultRefreshTokenExpiry
	}

	if c.Issuer == "" {
		c.Issuer = "playone-backend"
	}

	if c.MaxTokensPerUser <= 0 {
		c.MaxTokensPerUser = token.MaxTokensPerUser
	}

	if c.MaxTokensPerDevice <= 0 {
		c.MaxTokensPerDevice = token.MaxTokensPerDevice
	}

	return nil
}
