package main

import (
	"os"
	"os/signal"
	"syscall"
	"time"

	"nearle/config"
	"nearle/db"
	"nearle/middlewares"
	"nearle/routes"
	"nearle/utils"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/joho/godotenv"
)

func main() {

	_ = godotenv.Load()
	cfg := config.Load()

	app := fiber.New()

	app.Use(cors.New(cors.Config{
		AllowHeaders:     "Origin,Content-Type,Accept,Authorization",
		AllowOrigins:     "http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003,http://localhost:3004,http://localhost:3005,https://console.nearlexpress.com,https://app.nearlexpress.com,https://admin.nearlexpress.com,https://developer.nearlexpress.com", // 🔥 simplify (or keep your domains)
		AllowCredentials: true,
		AllowMethods:     "GET,POST,PUT,DELETE,PATCH,OPTIONS",
	}))

	app.Use(middlewares.ZapLogger())

	utils.Info("Connecting to database...")

	db.Connect()
	db.InitRedis()

	utils.Info("All connections established!")

	routes.LiveSetup(app)

	go func() {
		utils.Info("Server starting", "port", cfg.Port)
		if err := app.Listen(":" + cfg.Port); err != nil {
			utils.Logger.Fatalf("Server failed: %v", err)
		}
	}()

	gracefulShutdown()
}

func gracefulShutdown() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)

	<-c
	utils.Info("Shutting down...")

	db.CloseDB()

	time.Sleep(2 * time.Second)
	utils.Info("Shutdown complete")
}
