package main

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

	"erp-mvp/core-service/internal/api"
	"erp-mvp/core-service/internal/config"
	"erp-mvp/core-service/internal/database"
	"erp-mvp/core-service/internal/logger"
)

func main() {
	// Инициализация логгера
	logger := logger.New()

	// Загрузка конфигурации
	cfg, err := config.Load()
	if err != nil {
		logger.Fatal("Failed to load config", err)
	}

	// Подключение к базе данных
	db, err := database.Connect(cfg.Database)
	if err != nil {
		logger.Fatal("Failed to connect to database", err)
	}
	defer db.Close()

	// Создание API сервера
	server := api.NewServer(cfg, db, logger)

	// Запуск HTTP сервера
	go func() {
		logger.Info("Starting HTTP server on", cfg.Server.Port)
		if err := server.Start(); err != nil && err != http.ErrServerClosed {
			logger.Fatal("Failed to start server", err)
		}
	}()

	// Graceful shutdown
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.Info("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		logger.Fatal("Server forced to shutdown", err)
	}

	logger.Info("Server exited")
}
