package config

import (
	"encoding/json"

	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/orm"
	"github.com/perfect-panel/server/pkg/signature"
	"github.com/perfect-panel/server/pkg/trace"
)

type Config struct {
	Model         string                  `yaml:"Model" default:"prod"`
	Host          string                  `yaml:"Host" default:"0.0.0.0"`
	Port          int                     `yaml:"Port" default:"8080"`
	Debug         bool                    `yaml:"Debug" default:"false"`
	TLS           TLS                     `yaml:"TLS"`
	JwtAuth       JwtAuth                 `yaml:"JwtAuth"`
	Logger        logger.LogConf          `yaml:"Logger"`
	MySQL         orm.Config              `yaml:"MySQL"`
	Redis         RedisConfig             `yaml:"Redis"`
	Site          SiteConfig              `yaml:"Site"`
	Node          NodeConfig              `yaml:"Node"`
	Mobile        MobileConfig            `yaml:"Mobile"`
	Email         EmailConfig             `yaml:"Email"`
	Device        DeviceConfig            `yaml:"device"`
	AppSignature  signature.SignatureConf `yaml:"AppSignature"`
	Signature     Signature               `yaml:"Signature"`
	Verify        Verify                  `yaml:"Verify"`
	VerifyCode    VerifyCode              `yaml:"VerifyCode"`
	Register      RegisterConfig          `yaml:"Register"`
	Subscribe     SubscribeConfig         `yaml:"Subscribe"`
	Invite        InviteConfig            `yaml:"Invite"`
	Kutt          KuttConfig              `yaml:"Kutt"`
	OpenInstall   OpenInstallConfig       `yaml:"OpenInstall"`
	Loki          LokiConfig              `yaml:"Loki"`
	Telegram      Telegram                `yaml:"Telegram"`
	Log           Log                     `yaml:"Log"`
	Currency      Currency                `yaml:"Currency"`
	Trace         trace.Config            `yaml:"Trace"`
	S3            S3Config                `yaml:"S3"`
	Administrator struct {
		Email    string `yaml:"Email" default:"admin@ppanel.dev"`
		Password string `yaml:"Password" default:"password"`
	} `yaml:"Administrator"`
}

type S3Config struct {
	Enable               bool   `yaml:"Enable" default:"false"`
	Region               string `yaml:"Region" default:""`
	Bucket               string `yaml:"Bucket" default:""`
	Endpoint             string `yaml:"Endpoint" default:""`
	AccessKey            string `yaml:"AccessKey" default:""`
	SecretKey            string `yaml:"SecretKey" default:""`
	SessionToken         string `yaml:"SessionToken" default:""`
	Prefix               string `yaml:"Prefix" default:"app-upload"`
	PublicBaseURL        string `yaml:"PublicBaseURL" default:""`
	UsePathStyle         bool   `yaml:"UsePathStyle" default:"false"`
	PresignExpireSeconds int64  `yaml:"PresignExpireSeconds" default:"300"`
	MaxUploadSize        int64  `yaml:"MaxUploadSize" default:"104857600"`
	AllowedContentTypes  string `yaml:"AllowedContentTypes" default:"application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/octet-stream,text/plain,application/json"`
}

type RedisConfig struct {
	Host         string `yaml:"Host" default:"localhost:6379"`
	Pass         string `yaml:"Pass" default:""`
	DB           int    `yaml:"DB" default:"0"`
	PoolSize     int    `yaml:"PoolSize" default:"100"`    // 连接池大小（最大连接数）
	MinIdleConns int    `yaml:"MinIdleConns" default:"10"` // 最小空闲连接数
	MaxRetries   int    `yaml:"MaxRetries" default:"3"`    // 最大重试次数
	PoolTimeout  int    `yaml:"PoolTimeout" default:"4"`   // 连接池超时时间（秒）
	IdleTimeout  int    `yaml:"IdleTimeout" default:"300"` // 空闲连接超时时间（秒）
	MaxConnAge   int    `yaml:"MaxConnAge" default:"0"`    // 连接最大生命周期（秒），0表示不限制
	DialTimeout  int    `yaml:"DialTimeout" default:"5"`   // 连接超时时间（秒）
	ReadTimeout  int    `yaml:"ReadTimeout" default:"3"`   // 读超时时间（秒）
	WriteTimeout int    `yaml:"WriteTimeout" default:"3"`  // 写超时时间（秒）
}

type JwtAuth struct {
	AccessSecret string `yaml:"AccessSecret"`
	AccessExpire int64  `yaml:"AccessExpire" default:"31536000"` // JWT 签发有效期，单位秒，默认 365 天
}

type Verify struct {
	TurnstileSiteKey    string `yaml:"TurnstileSiteKey" default:""`
	TurnstileSecret     string `yaml:"TurnstileSecret" default:""`
	LoginVerify         bool   `yaml:"LoginVerify" default:"false"`
	RegisterVerify      bool   `yaml:"RegisterVerify" default:"false"`
	ResetPasswordVerify bool   `yaml:"ResetPasswordVerify" default:"false"`
}

type SubscribeConfig struct {
	SingleModel     bool   `yaml:"SingleModel" default:"false"`
	SubscribePath   string `yaml:"SubscribePath" default:"/v1/subscribe/config"`
	SubscribeDomain string `yaml:"SubscribeDomain" default:""`
	PanDomain       bool   `yaml:"PanDomain" default:"false"`
	UserAgentLimit  bool   `yaml:"UserAgentLimit" default:"false"`
	UserAgentList   string `yaml:"UserAgentList" default:""`
}

type RegisterConfig struct {
	StopRegister              bool   `yaml:"StopRegister" default:"false"`
	EnableTrial               bool   `yaml:"EnableTrial" default:"false"`
	EnableTrialEmailWhitelist bool   `yaml:"EnableTrialEmailWhitelist" default:"true"`
	TrialSubscribe            int64  `yaml:"TrialSubscribe" default:"0"`
	TrialTime                 int64  `yaml:"TrialTime" default:"0"`
	TrialTimeUnit             string `yaml:"TrialTimeUnit" default:""`
	TrialEmailDomainWhitelist string `yaml:"TrialEmailDomainWhitelist" default:""`
	IpRegisterLimit           int64  `yaml:"IpRegisterLimit" default:"0"`
	IpRegisterLimitDuration   int64  `yaml:"IpRegisterLimitDuration" default:"0"`
	EnableIpRegisterLimit     bool   `yaml:"EnableIpRegisterLimit" default:"false"`
	DeviceLimit               int64  `yaml:"DeviceLimit" default:"2"`
}

type EmailConfig struct {
	Enable                     bool              `yaml:"Enable" default:"true"`
	Platform                   string            `yaml:"platform"`
	PlatformConfig             string            `yaml:"platform_config"`
	EnableVerify               bool              `yaml:"enable_verify"`
	EnableNotify               bool              `yaml:"enable_notify"`
	EnableDomainSuffix         bool              `yaml:"enable_domain_suffix"`
	DomainSuffixList           string            `yaml:"domain_suffix_list"`
	VerifyEmailTemplate        string            `yaml:"verify_email_template"`
	VerifyEmailTemplates       map[string]string `yaml:"verify_email_templates"`
	ExpirationEmailTemplate    string            `yaml:"expiration_email_template"`
	MaintenanceEmailTemplate   string            `yaml:"maintenance_email_template"`
	TrafficExceedEmailTemplate string            `yaml:"traffic_exceed_email_template"`
	DeleteAccountEmailTemplate string            `yaml:"delete_account_email_template"`
}

type MobileConfig struct {
	Enable          bool     `yaml:"Enable" default:"true"`
	Platform        string   `yaml:"platform"`
	PlatformConfig  string   `yaml:"platform_config"`
	EnableVerify    bool     `yaml:"enable_verify"`
	EnableWhitelist bool     `yaml:"enable_whitelist"`
	Whitelist       []string `yaml:"whitelist"`
}

type DeviceConfig struct {
	Enable         bool   `yaml:"enable" default:"true"`
	ShowAds        bool   `yaml:"show_ads"`
	EnableSecurity bool   `yaml:"enable_security"`
	OnlyRealDevice bool   `yaml:"only_real_device"`
	SecuritySecret string `yaml:"security_secret"`
}

type Signature struct {
	EnableSignature bool `yaml:"EnableSignature" default:"false"`
}

type SiteConfig struct {
	Host       string `yaml:"Host" default:""`
	SiteName   string `yaml:"SiteName" default:""`
	SiteDesc   string `yaml:"SiteDesc" default:""`
	SiteLogo   string `yaml:"SiteLogo" default:""`
	Keywords   string `yaml:"Keywords" default:""`
	CustomHTML string `yaml:"CustomHTML" default:""`
	CustomData string `yaml:"CustomData" default:""`
}

type NodeConfig struct {
	NodeSecret             string         `yaml:"NodeSecret" default:""`
	NodePullInterval       int64          `yaml:"NodePullInterval" default:"60"`
	NodePushInterval       int64          `yaml:"NodePushInterval" default:"60"`
	TrafficReportThreshold int64          `yaml:"TrafficReportThreshold" default:"0"`
	IPStrategy             string         `yaml:"IPStrategy" default:""`
	DNS                    []NodeDNS      `yaml:"DNS"`
	Block                  []string       `yaml:"Block" `
	Outbound               []NodeOutbound `yaml:"Outbound"`
}

func (n *NodeConfig) Marshal() ([]byte, error) {
	type Alias NodeConfig
	return json.Marshal(&struct {
		*Alias
	}{
		Alias: (*Alias)(n),
	})
}

func (n *NodeConfig) Unmarshal(data []byte) error {
	type Alias NodeConfig
	aux := &struct {
		*Alias
	}{
		Alias: (*Alias)(n),
	}
	return json.Unmarshal(data, &aux)
}

type NodeDNS struct {
	Proto   string   `json:"proto"`
	Address string   `json:"address"`
	Domains []string `json:"domains"`
}

func (n *NodeDNS) Marshal() ([]byte, error) {
	type Alias NodeDNS
	return json.Marshal(&struct {
		*Alias
	}{
		Alias: (*Alias)(n),
	})
}

func (n *NodeDNS) Unmarshal(data []byte) error {
	type Alias NodeDNS
	aux := &struct {
		*Alias
	}{
		Alias: (*Alias)(n),
	}
	return json.Unmarshal(data, &aux)
}

type NodeOutbound struct {
	Name     string   `json:"name"`
	Protocol string   `json:"protocol"`
	Address  string   `json:"address"`
	Port     int64    `json:"port"`
	Password string   `json:"password"`
	Rules    []string `json:"rules"`
}

func (n *NodeOutbound) Marshal() ([]byte, error) {
	type Alias NodeOutbound
	return json.Marshal(&struct {
		*Alias
	}{
		Alias: (*Alias)(n),
	})
}

type File struct {
	Host    string         `yaml:"Host" default:"0.0.0.0"`
	Port    int            `yaml:"Port" default:"8080"`
	TLS     TLS            `yaml:"TLS"`
	Debug   bool           `yaml:"Debug" default:"true"`
	JwtAuth JwtAuth        `yaml:"JwtAuth"`
	Logger  logger.LogConf `yaml:"Logger"`
	MySQL   orm.Config     `yaml:"MySQL"`
	Redis   RedisConfig    `yaml:"Redis"`
}

type InviteConfig struct {
	ForcedInvite       bool  `yaml:"ForcedInvite" default:"false"`
	ReferralPercentage int64 `yaml:"ReferralPercentage" default:"0"`
	OnlyFirstPurchase  bool  `yaml:"OnlyFirstPurchase" default:"false"`
	GiftDays           int64 `yaml:"GiftDays" default:"3"`
}

// KuttConfig Kutt 短链接服务配置
type KuttConfig struct {
	Enable    bool   `yaml:"Enable" default:"false"` // 是否启用 Kutt 短链接
	ApiURL    string `yaml:"ApiURL" default:""`      // Kutt API 地址
	ApiKey    string `yaml:"ApiKey" default:""`      // Kutt API 密钥
	TargetURL string `yaml:"TargetURL" default:""`   // 目标注册页面基础 URL
	Domain    string `yaml:"Domain" default:""`      // 短链接域名 (例如: getsapp.net)
}

// OpenInstallConfig OpenInstall 配置
type OpenInstallConfig struct {
	Enable bool   `yaml:"Enable" default:"false"` // 是否启用 OpenInstall
	AppKey string `yaml:"AppKey" default:""`      // OpenInstall AppKey (SDK使用)
	ApiKey string `yaml:"ApiKey" default:""`      // OpenInstall 数据接口 ApiKey
}

// LokiConfig Loki 日志查询配置
type LokiConfig struct {
	Enable bool   `yaml:"Enable" default:"false"`              // 是否启用 Loki 查询
	URL    string `yaml:"URL" default:"http://localhost:3100"` // Loki 服务地址
}

type Telegram struct {
	Enable        bool   `yaml:"Enable" default:"false"`
	BotID         int64  `yaml:"BotID" default:""`
	BotName       string `yaml:"BotName" default:""`
	BotToken      string `yaml:"BotToken" default:""`
	GroupChatID   string `yaml:"GroupChatID" default:""`
	EnableNotify  bool   `yaml:"EnableNotify" default:"false"`
	WebHookDomain string `yaml:"WebHookDomain" default:""`
}

type TLS struct {
	Enable   bool   `yaml:"Enable" default:"false"`
	CertFile string `yaml:"CertFile" default:""`
	KeyFile  string `yaml:"KeyFile" default:""`
}

type VerifyCode struct {
	VerifyCodeExpireTime int64 `yaml:"VerifyCodeExpireTime" default:"900"`
	VerifyCodeLimit      int64 `yaml:"VerifyCodeLimit" default:"15"`
	VerifyCodeInterval   int64 `yaml:"VerifyCodeInterval" default:"60"`
}

type Log struct {
	AutoClear bool  `yaml:"AutoClear" default:"true"`
	ClearDays int64 `yaml:"ClearDays" default:"7"`
}

type NodeDBConfig struct {
	NodeSecret             string
	NodePullInterval       int64
	NodePushInterval       int64
	TrafficReportThreshold int64
	IPStrategy             string
	DNS                    string
	Block                  string
	Outbound               string
}

type Currency struct {
	Unit      string `yaml:"Unit" default:"CNY"`
	Symbol    string `yaml:"Symbol" default:"USD"`
	AccessKey string `yaml:"AccessKey" default:""`
}
