package system

import (
	"context"
	"encoding/json"
	"kra/internal/biz/system"
	"kra/internal/routecatalog"
	"kra/internal/service/dto"
	"kra/internal/utils/routepath"
)

type SystemConfigService struct {
	uc       *system.SystemConfigUsecase
	settings system.RuntimeSettings
}

func NewSystemConfigService(uc *system.SystemConfigUsecase, settings system.RuntimeSettings) *SystemConfigService {
	return &SystemConfigService{uc: uc, settings: settings}
}

func (s *SystemConfigService) IsInitialized(ctx context.Context) (bool, error) {
	return s.uc.IsInitialized(ctx)
}

func (s *SystemConfigService) PersistConfig(ctx context.Context) error {
	return s.uc.PersistConfig(ctx)
}
func (s *SystemConfigService) ReloadConfig(ctx context.Context) error { return s.uc.ReloadConfig(ctx) }
func (s *SystemConfigService) DiskMountPoints() []string              { return s.uc.DiskMountPoints() }
func (s *SystemConfigService) SystemConfig() (json.RawMessage, error) {
	return s.uc.ConfigurationJSON()
}
func (s *SystemConfigService) SaveSystemConfig(ctx context.Context, req *dto.SetSystemConfigRequest) error {
	return s.uc.SaveConfigurationJSON(ctx, req.Config)
}

func (s *SystemConfigService) Initialize(ctx context.Context, input *dto.DatabaseInitRequest, apis []*system.API) error {
	driver, config := input.DBType, ""
	switch driver {
	case "mysql":
		config = "charset=utf8mb4&parseTime=True&loc=Local"
	case "pgsql":
		config = "sslmode=disable TimeZone=Asia/Shanghai"
	case "sqlite", "mssql":
	default:
		driver = "mysql"
		config = "charset=utf8mb4&parseTime=True&loc=Local"
	}
	return s.uc.Initialize(ctx, &system.DatabaseConfig{Driver: driver, Host: input.Host, Port: input.Port, User: input.UserName, Password: input.Password, Name: input.DBName, Path: input.DBPath, Config: config, Template: input.Template, AdminPassword: input.AdminPassword, APIs: apis})
}

func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *dto.DatabaseInitRequest, routes []dto.Route) error {
	apis := make([]*system.API, 0, len(routes))
	for _, route := range routes {
		path := routepath.Normalize(route.Path, s.settings.RouterPrefix())
		descriptor := routecatalog.Describe(route.Method, path)
		apis = append(apis, &system.API{Path: path, Method: route.Method, APIGroup: descriptor.Group, Description: descriptor.Description})
	}
	return s.Initialize(ctx, input, apis)
}

func (s *SystemConfigService) ServerInfo(ctx context.Context) (*dto.ServerInfoResponse, error) {
	value, err := s.uc.ServerInfo(ctx)
	if err != nil {
		return nil, err
	}
	diskInfo := make([]dto.ServerDiskResponse, 0, len(value.Disk))
	for _, disk := range value.Disk {
		diskInfo = append(diskInfo, dto.ServerDiskResponse{MountPoint: disk.MountPoint, UsedMB: disk.UsedMB, UsedGB: disk.UsedGB, TotalMB: disk.TotalMB, TotalGB: disk.TotalGB, UsedPercent: disk.UsedPercent})
	}
	return &dto.ServerInfoResponse{OS: dto.ServerOSResponse{GOOS: value.GOOS, NumCPU: value.NumCPU, Compiler: value.Compiler, GoVersion: value.GoVersion, NumGoroutine: value.NumGoroutine}, CPU: dto.ServerCPUResponse{CPUs: value.CPUs, Cores: value.Cores}, RAM: dto.ServerRAMResponse{UsedMB: value.UsedMB, TotalMB: value.TotalMB, UsedPercent: value.UsedPercent}, Disk: diskInfo}, nil
}
