package main

import (
	"context"
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"

	"hyapp/pkg/logx"
	"hyapp/services/lucky-gift-service/internal/app"
	"hyapp/services/lucky-gift-service/internal/config"
)

// main 启动 lucky-gift-service。
// 服务启动失败必须直接退出，避免 room/luck-gateway 继续把抽奖请求发到一个没有 owner 的地址。
func main() {
	configPath := flag.String("config", "services/lucky-gift-service/configs/config.yaml", "path to lucky-gift-service config")
	flag.Parse()

	cfg, err := config.Load(*configPath)
	if err != nil {
		log.Fatal(err)
	}
	if err := logx.Init(cfg.Log.WithRuntimeFields(cfg.ServiceName, cfg.Environment, cfg.NodeID)); err != nil {
		log.Fatal(err)
	}

	application, err := app.New(cfg)
	if err != nil {
		fatalRuntime("lucky_gift_app_new_failed", err)
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	errCh := make(chan error, 1)
	go func() {
		errCh <- application.Run()
	}()

	select {
	case <-ctx.Done():
		application.Close()
	case err := <-errCh:
		if err != nil {
			fatalRuntime("lucky_gift_service_run_failed", err)
		}
	}
}

func fatalRuntime(message string, err error) {
	logx.Error(context.Background(), message, err)
	os.Exit(1)
}
