package main

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

	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/config"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api"
	"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/logger"
	"go.uber.org/zap"
)

func main() {
	// Load configuration
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// Initialize logger
	l := logger.New(cfg.LogLevel)
	defer l.Sync()

	// Setup router
	router := api.SetupRouter(cfg, l)

	// Configure server
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", cfg.Server.Port),
		Handler:      router,
		ReadTimeout:  time.Duration(cfg.Server.ReadTimeoutSeconds) * time.Second,
		WriteTimeout: time.Duration(cfg.Server.WriteTimeoutSeconds) * time.Second,
		IdleTimeout:  time.Duration(cfg.Server.IdleTimeoutSeconds) * time.Second,
	}

	// Start server
	l.Info("Starting server", zap.Int("port", cfg.Server.Port)) // Convert cfg.Server.Port to zap.Int
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			l.Fatal("Server failed", zap.Error(err)) // Convert err to zap.Error
		}
	}()

	// Wait for interrupt signal to gracefully shut down the server
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	l.Info("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := server.Shutdown(ctx); err != nil {
		l.Fatal("Server failed", zap.Error(err)) // Convert err to zap.Error
	}

	l.Info("Server exiting")
}
