package main

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

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

func main() {
	configPath := flag.String("config", "services/statistics-service/configs/config.yaml", "path to statistics-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("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("service_run_failed", err)
		}
	}
}

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