package main

import (
	"fmt"
	"log"

	"github.com/gin-gonic/gin"
	"github.com/monitor/backend/config"
	"github.com/monitor/backend/internal/device"
	"github.com/monitor/backend/internal/handler"
	"github.com/monitor/backend/internal/storage"
)

// StartServer 启动服务器
func StartServer() {
	// 加载配置
	cfg, err := config.LoadConfig()
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 创建存储实例
	store := storage.NewStorage(cfg)
	defer store.Close()

	// 创建Gin引擎
	r := gin.Default()

	// 设置CORS
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 设置全局存储实例
	handler.SetStorage(store)

	// 初始化设备存储
	deviceStore := device.NewMemoryStorage()
	handler.SetDeviceStorage(deviceStore)

	// 注册路由
	handler.RegisterRoutes(r)

	// 启动服务器
	addr := fmt.Sprintf(":%d", cfg.Server.Port)
	log.Printf("Server starting on %s", addr)
	if err := r.Run(addr); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

func main() {
	StartServer()
}
