package main

import (
	"fmt"
	"net/http"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/billing2/config"
	"github.com/pingcap/dbaas/billing2/db"
	"github.com/pingcap/dbaas/billing2/handler/cachehandler"
	"github.com/pingcap/dbaas/billing2/handler/eventbushandler"
	"github.com/pingcap/dbaas/billing2/promotion"
	"github.com/pingcap/dbaas/billing2/utils/log"
	"github.com/pingcap/dbaas/billing2/utils/panicIf"
	"github.com/pingcap/dbaas/billing2/utils/sentry"
	"github.com/pingcap/dbaas/billing2/version"
	"go.uber.org/zap"
)

func main() {
	gin.DisableConsoleColor()
	panicIf.Error(config.Init())

	_, err := db.Initialize()
	panicIf.Error(err)
	cachehandler.Init()
	panicIf.Error(sentry.SetupLoggerAndSentry())

	// Register promotion event handlers (tenant_registered, tenant-payable)
	panicIf.Error(promotion.RegisterEventHandlers())
	panicIf.Error(eventbushandler.Get().Run())

	// Start the promotion checker jobs (gocron, async)
	promotion.RunChecker()

	engine := gin.Default()
	engine.GET("/version", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"hash": version.GitHash}) })
	pprof.Register(engine)

	log.Fatal("start promotion worker failed", zap.Error(engine.Run(fmt.Sprintf(":%d", config.Get().GetInt(config.BillingServerPort)))))
}
