package main

import (
	"flag"
	"fmt"

	"sundynix-micro-go/app/system/rpc/internal/config"
	"sundynix-micro-go/app/system/rpc/internal/server"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/internal/task"
	"sundynix-micro-go/app/system/rpc/system"
	"sundynix-micro-go/common/utils/timer"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/core/stat"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

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

func main() {
	flag.Parse()
	stat.DisableLog()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		system.RegisterSystemServiceServer(grpcServer, server.NewSystemServiceServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// 初始化定时任务系统
	cronTimer := timer.NewTimerTask()
	defer cronTimer.Close()

	// 注册定时清理操作日志任务 (每天凌晨 3:00 执行)
	cleanJob := task.NewCleanOperLogJob(ctx)
	_, err := cronTimer.AddTaskByJob("systemCron", "0 3 * * *", cleanJob, "cleanOperLogTask")
	if err != nil {
		logx.Errorf("❌ 注册定时清理操作日志任务失败: %v", err)
	} else {
		logx.Infof("✅ 注册定时清理操作日志任务成功 (每天凌晨3点)")
	}

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
