package service

import (
	"context"

	"kra/internal/biz"
	"kra/internal/service/dto"
)

func (s *SystemConfigService) Initialize(ctx context.Context, input *dto.DatabaseInitRequest, apis []*biz.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:
		// The compatible initialization flow treats an omitted or unknown dbType as MySQL during
		// initialization rather than rejecting it as an unsupported driver.
		driver = "mysql"
		config = "charset=utf8mb4&parseTime=True&loc=Local"
	}
	return s.uc.Initialize(ctx, &biz.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([]*biz.API, 0, len(routes))
	for _, route := range routes {
		path := NormalizeRoutePath(route.Path, s.settings.RouterPrefix())
		group, description := RouteMetadata(route.Method, path)
		apis = append(apis, &biz.API{Path: path, Method: route.Method, APIGroup: group, Description: description})
	}
	return s.Initialize(ctx, input, apis)
}
