package main

import (
	"fmt"
	configs "goFiber/config"
	database "goFiber/database/config"
	migrasyon "goFiber/database/migrate"
	"goFiber/middlewares"
	"goFiber/routes"
	"log"
	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/adaptor"
	"github.com/gofiber/fiber/v3/middleware/session"
	redisStorage "github.com/gofiber/storage/redis/v3"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"go.uber.org/zap"
)

var SessionStore *session.Store

func init() {
	configs.LoadConfig()
	database.ConnectDB()
	database.ConnectRedis()

	migrasyon.Migrate()

	// Session store: Redis varsa Redis-backed storage, yoksa in-memory
	if database.RedisOptions != nil {
		// Use URL so storage package parses it correctly
		cfg := redisStorage.Config{
			URL: configs.AppConfig.RedisUrl,
		}

		// If TLSConfig was set during parse, copy it over
		if database.RedisOptions.TLSConfig != nil {
			cfg.TLSConfig = database.RedisOptions.TLSConfig
		}

		storage := redisStorage.New(cfg)
		SessionStore = session.NewStore(session.Config{
			Storage: storage,
		})
		log.Println("Session store: using Redis-backed storage")
	} else {
		// Basit: her durumda in-memory session store kullan (opsiyonel: Redis kullanımı ileride eklenebilir)
		SessionStore = session.NewStore()
		log.Println("Session store: using in-memory storage")
	}

	log.Println("Init Uygulandı !!")
}

// @title AreS Fiber API Server
// @version 1.0
// @description This is a sample server for AreS Fiber API.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /
// @schemes http

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.
func main() {
	logger, _ := zap.NewProduction()
	zap.ReplaceGlobals(logger)
	defer logger.Sync()
	sugar := logger.Sugar()

	app := fiber.New(fiber.Config{
		AppName:      "AreS Fiber API Server",
		IdleTimeout:  5 * time.Second,
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
		Concurrency:  256 * 1024,
	})

	//zap.L().Info("Fiber uygulaması başlatıldı")
	// prevent 'unused variable' warning for SessionStore (it may be used elsewhere)
	_ = SessionStore
	app.Get("/metric", adaptor.HTTPHandler(promhttp.Handler()))
	app.Get("/health", func(c fiber.Ctx) error {
		return c.JSON(fiber.Map{
			"status": "ok",
		})
	})

	// Serve uploads folder dynamically so URLs like /uploads/settings/xxx.png are accessible
	app.Get("/uploads/*", func(c fiber.Ctx) error {
		file := c.Params("*")
		return c.SendFile("./uploads/" + file)
	})

	app.Use(middlewares.DynamicCORS())
	routes.RouterUser(app)

	port := configs.AppConfig.Port
	if port == "" {
		port = "8080" // Fallback port
	}

	sugar.Info("Server Bu Porta Başladı: " + port)
	_ = app.Listen(fmt.Sprintf(":%s", port))
}
