package main

import (
	"GoMembership/internal/config"
	"GoMembership/internal/database"
	"GoMembership/internal/server"
	"GoMembership/pkg/logger"
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {

	logger.Info.Println("startup...")

	config.LoadConfig()

	err := database.Open(config.DB.Path, config.Recipients.AdminEmail)
	if err != nil {
		logger.Error.Fatalf("Couldn't init database: %v", err)
	}

	defer func() {
		if err := database.Close(); err != nil {
			logger.Error.Fatalf("Failed to close database: %v", err)
		}
	}()

	go server.Run()

	gracefulShutdown()
}

func gracefulShutdown() {
	// Create a channel to listen for OS signals
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

	// Block until a signal is received
	<-stop
	logger.Info.Println("Received shutdown signal")

	// Create a context with a timeout for the shutdown process
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// Call the server's shutdown function
	if err := server.Shutdown(ctx); err != nil {
		logger.Error.Fatalf("Error during  Server  shutdown: %#v", err)
	} else {
		logger.Info.Println("Server gracefully stopped")
	}
}
