package main

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

	"realtime-gateway/internal/config"
	"realtime-gateway/internal/gateway"
	"realtime-gateway/internal/logging"
)

func main() {
	configPath := flag.String("config", "./config/dev.json", "path to config file")
	flag.Parse()

	cfg, err := config.Load(*configPath)
	if err != nil {
		panic(err)
	}

	logger := logging.New()
	app, err := gateway.NewServer(cfg, logger)
	if err != nil {
		logger.Error("failed to create server", "error", err)
		os.Exit(1)
	}

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

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

	select {
	case <-ctx.Done():
		logger.Info("shutdown signal received")
	case err := <-errCh:
		if err != nil {
			logger.Error("server stopped with error", "error", err)
			os.Exit(1)
		}
	}
}
