package main

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"aijianzhan/platform/internal/config"
	"aijianzhan/platform/internal/handler"
	"aijianzhan/platform/internal/license"
	"aijianzhan/platform/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/platform.yaml", "config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	server := rest.MustNewServer(c.RestConf, rest.WithCors())
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	server.Use(func(next http.HandlerFunc) http.HandlerFunc {
		return license.Middleware(ctx.License)(next)
	})
	handler.RegisterHandlers(server, ctx)

	runCtx, cancel := context.WithCancel(context.Background())
	defer cancel()
	if ctx.DBSync != nil {
		ctx.DBSync.StartAll(runCtx)
		ttlDays := c.DBSync.LwwAuditTTLDays
		if ttlDays <= 0 {
			ttlDays = 90
		}
		go func() {
			t := time.NewTicker(6 * time.Hour)
			defer t.Stop()
			purge := func() {
				cutoff := time.Now().UTC().Add(-time.Duration(ttlDays) * 24 * time.Hour)
				n, err := ctx.DBSync.Store().PurgeLwwOverridesBefore(cutoff)
				if err != nil {
					fmt.Printf("dbsync lww purge: %v\n", err)
					return
				}
				if n > 0 {
					fmt.Printf("dbsync lww purge: removed %d\n", n)
				}
			}
			purge()
			for {
				select {
				case <-runCtx.Done():
					return
				case <-t.C:
					purge()
				}
			}
		}()
	}

	go func() {
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
		<-ch
		cancel()
		server.Stop()
	}()

	fmt.Printf("platform starting at %s:%d (memoryMode=%v dryRun=%v dbsync=%v)\n",
		c.Host, c.Port, ctx.MemoryMode, c.DryRun, ctx.DBSync != nil)
	server.Start()
}
