package main

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

	"github.com/rs/zerolog/log"

	"route256/loms/internal/app"
	"route256/loms/internal/infra/tracing"
)

func main() {
	shut, err := tracing.InitOTLP(context.Background(), "cart", "jaeger:4318")
	if err != nil {
		log.Fatal().Err(err).Msg("tracing init failed")
	}
	defer func() {
		_ = shut(context.Background())
	}()

	srv, err := app.NewApp(os.Getenv("CONFIG_FILE"))
	if err != nil {
		log.Fatal().Err(err).Msg("failed creating app")
	}

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

	go func() {
		if err := srv.ListenAndServe(ctx); err != nil && err != http.ErrServerClosed {
			log.Fatal().Err(err).Msg("serving error")
		}
	}()

	<-ctx.Done()
	log.Info().Msg("shutdown signal received")

	shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Error().Err(err).Msg("graceful shutdown failed")
	} else {
		log.Info().Msg("server stopped gracefully")
	}
}
