package app

import (
	"encoding/json"
	"github.com/gofiber/fiber/v2"
	"github.com/spf13/viper"
	"matrix-common/pkg/logger"
	"matrix-middle-service/internel/middleware"
	"matrix-middle-service/internel/route"
	"matrix-middle-service/pkg/config"
	"matrix-middle-service/pkg/database"
	fib "matrix-middle-service/pkg/utils/fiber"
	"matrix-middle-service/pkg/utils/nanoid"
	"matrix-middle-service/pkg/utils/sonyflake"
	"time"
)

var app *fiber.App
var conf = new(config.Conf)

func CreateApp(c *config.Conf) *fiber.App {
	return fiber.New(fiber.Config{
		JSONEncoder:   json.Marshal,
		JSONDecoder:   json.Unmarshal,
		Prefork:       c.Server.PreFork,
		CaseSensitive: c.Server.CaseSensitive,
		StrictRouting: c.Server.StrictRouting,
		ServerHeader:  c.Server.ServerHeader,
		ErrorHandler:  route.GlobalErrorHandler(),
	})
}

func Run() {
	err := viper.Unmarshal(conf)
	if err != nil {
		logger.Log().Fatalf("配置文件解析失败: %s, 请检查配置是否有误", err)
	}
	Shutdown()

	// 初始化数据源
	fib.Exec(func() {
		InitApp(conf)
	})

	// 创建 fiber 服务器
	app = CreateApp(conf)
	middleware.UseCorsMiddleWare(app)
	// 设置路由
	route.SetupRoute(app, conf)

	// 启动完成
	app.Hooks().OnListen(func() error {
		fib.Exec(func() {
			logger.Log().Info("[√] [服务启动完成]")
		})
		return nil
	})
	if err := app.Listen(conf.Server.Addr); err != nil {
		logger.Log().Fatalf("[x] [Fiber] 致命错误: %s", err)
	}
}

func InitApp(conf *config.Conf) {
	database.Init(conf.DataSources)
	if err := database.Open(); err != nil {
		logger.Log().Fatal(err)
	}

	sonyflake.Init(conf.SonyFlake)
	nanoid.Init(conf.NanoIdConfig)
}

func Shutdown() {
	if app == nil {
		return
	}

	fib.Exec(func() {
		database.Close()
	})

	logger.Log().Info("关闭服务")
	timeout := 5 * time.Second
	err := app.ShutdownWithTimeout(timeout)
	if err != nil {
		logger.Log().Fatal(err)
	}
}
