package main

import (
	"fmt"
	"licserver/internal/api"
	"licserver/internal/model"
	"licserver/internal/service"
	"licserver/internal/utils"
	"log"
	"os"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// 初始化管理员账号
func initAdminUser(db *gorm.DB) error {
	var count int64
	db.Model(&model.User{}).Where("role = ?", "admin").Count(&count)

	// 如果没有管理员账号，创建默认管理员
	if count == 0 {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte("admin"), bcrypt.DefaultCost)
		if err != nil {
			return err
		}

		admin := model.User{
			Username: "admin",
			Password: string(hashedPassword),
			Email:    "admin@example.com",
			Role:     "admin",
		}

		if err := db.Create(&admin).Error; err != nil {
			return err
		}
		log.Println("已创建默认管理员账号：admin/admin")
	}
	return nil
}

func main() {
	// 加载配置
	config, err := utils.LoadConfig()
	if err != nil {
		log.Fatalf("无法加载配置: %v", err)
	}

	// 初始化数据库
	db, err := utils.InitDB(&config.Database)
	if err != nil {
		log.Fatalf("无法初始化数据库: %v", err)
	}

	// 初始化管理员账号
	if err := initAdminUser(db); err != nil {
		log.Fatalf("初始化管理员账号失败: %v", err)
	}

	// 初始化服务
	licenseService := service.NewLicenseService(db)
	userService := service.NewUserService(db, config)
	deviceService := service.NewDeviceService(db, licenseService)
	monitorService := service.NewMonitorService(db)
	uploadService := service.NewUploadService(db, config)
	siteService := service.NewSiteService(config)
	tokenService := service.NewTokenService(db)

	// 初始化处理器
	userHandler := api.NewUserHandler(userService)
	deviceHandler := api.NewDeviceHandler(deviceService)
	monitorHandler := api.NewMonitorHandler(monitorService)
	uploadHandler := api.NewUploadHandler(uploadService)
	siteHandler := api.NewSiteHandler(siteService)
	tokenHandler := api.NewTokenHandler(tokenService)
	licenseHandler := api.NewLicenseHandler(licenseService)

	// 设置路由
	router := api.SetupRouter(
		userHandler,
		deviceHandler,
		monitorHandler,
		config,
		uploadHandler,
		siteHandler,
		tokenHandler,
		licenseHandler,
	)

	// 创建必要的目录
	dirs := []string{
		"data",
		"uploads",
		"uploads/site",
		"static/uploads",
		"static/uploads/site",
		"web/static/lib",
	}
	for _, dir := range dirs {
		if err := os.MkdirAll(dir, 0755); err != nil {
			log.Fatalf("创建目录失败: %v", err)
		}
	}

	// 启动服务器
	addr := fmt.Sprintf(":%s", config.Server.Port)
	log.Printf("服务器启动在 %s", addr)
	if err := router.Run(addr); err != nil {
		log.Fatalf("服务器启动失败: %v", err)
	}
}
