package main

import (
	"context"
	"fmt"
	"net/http"

	"mini-chat/configs"
	"mini-chat/internal/cron"
	"mini-chat/internal/pkg/env"
	"mini-chat/internal/pkg/logger"
	"mini-chat/internal/pkg/shutdown"
	"mini-chat/internal/pkg/timeutil"
	"mini-chat/internal/repository/mysql"
	"mini-chat/internal/repository/mysql/dao"
	"mini-chat/internal/router"

	"go.uber.org/zap"
)

// @title mini-chat 接口文档
// @version v0.0.1

// @securityDefinitions.apikey  LoginVerifyToken
// @in                          header
// @name                        Authorization

// @BasePath /
func main() {
	// 初始化 MySQL
	dbRepo, err := mysql.New()
	if err != nil {
		panic(err)
	}

	// 初始化 自定义 Logger
	customLogger, err := logger.NewCustomLogger(dao.Use(dbRepo.GetDbW()),
		logger.WithDebugLevel(),      // 启用调试级别日志
		logger.WithOutputInConsole(), // 启用控制台输出
		logger.WithField("domain", fmt.Sprintf("%s[%s]", configs.ProjectName, env.Active().Value())),
		logger.WithTimeLayout(timeutil.CSTLayout),
		logger.WithFileRotationP(configs.ProjectAccessLogFile),
	)

	if err != nil {
		panic(err)
	}

	defer func() {
		_ = customLogger.Sync()
	}()

	// 初始化 Cron
	cronServer, err := cron.New(customLogger, dbRepo)
	if err != nil {
		panic(err)
	}
	cronServer.Start()

	// 初始化 HTTP 服务
	mux, err := router.NewHTTPMux(customLogger, dbRepo, cronServer)
	if err != nil {
		panic(err)
	}

	server := &http.Server{
		Addr:    configs.ProjectPort,
		Handler: mux,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			customLogger.Fatal("http server startup err", zap.Error(err))
		}
	}()

	// 优雅关闭
	shutdown.Close(
		func() {
			// 关闭 http server
			if err := server.Shutdown(context.TODO()); err != nil {
				customLogger.Error("server shutdown err", zap.Error(err))
			}

			// 关闭 db master (支持读写)
			if err := dbRepo.DbWClose(); err != nil {
				customLogger.Error("dbw close err", zap.Error(err))
			}

			// 关闭 db slave (仅支持读)
			if err := dbRepo.DbRClose(); err != nil {
				customLogger.Error("dbr close err", zap.Error(err))
			}

			// 关闭 cron
			if cronServer != nil {
				cronServer.Stop()
			}
		},
	)
}
