package main

// Swagger security definition for Bearer token (swaggo)
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Enter your bearer token in the format 'Bearer {token}'

import (
	config "ares/config"
	database "ares/database/config"
	"ares/database/migrate"
	"ares/database/seeder"
	_ "ares/docs"
	"ares/routes"
	"os"
	"time"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/static"
	"github.com/gofiber/template/html/v2"
	swag "github.com/swaggo/swag"
)

func init() {
	config.LoadConfig()
	database.ConnectDB()
	// database.ConnectDBPg()
	database.ConnectRedis()
	migrate.Migrate()
	// migrate.MigratePg()
	seeder.Seed()
	if config.Logger != nil {
		config.Logger.Info("Init Uygulandı !!")
	}

}
func main() {
	// Initialize standard Go html template engine
	// Use absolute path for safety
	cwd, _ := os.Getwd()
	engine := html.New(cwd+"/views", ".html")

	// Add helper function to handle *bool and bool in templates
	engine.AddFunc("isTrue", func(val interface{}) bool {
		if val == nil {
			return false
		}
		switch v := val.(type) {
		case bool:
			return v
		case *bool:
			if v == nil {
				return false
			}
			return *v
		default:
			return false
		}
	})

	engine.Reload(true) // Enable reload for development

	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,
		Views:        engine, // Register the views engine
	})

	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)
	})

	// Serve static files from public directory (CSS, JS, Assets)
	app.Use("/", static.New("./public"))

	// Register Routes
	// Serve generated swagger.json from registered docs (swag)
	app.Get("/swagger/swagger.json", func(c fiber.Ctx) error {
		doc, err := swag.ReadDoc("swagger")
		if err != nil {
			return c.Status(404).JSON(fiber.Map{"error": "swagger doc not found"})
		}
		return c.Type("json").SendString(doc)
	})
	// Simple Swagger UI page using CDN (points to /swagger/swagger.json)
	app.Get("/swagger/*", func(c fiber.Ctx) error {
		html := `<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Swagger UI</title>
		<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4/swagger-ui.css" />
	</head>
	<body>
		<div id="swagger-ui"></div>
		<script src="https://unpkg.com/swagger-ui-dist@4/swagger-ui-bundle.js"></script>
		<script>
			window.ui = SwaggerUIBundle({
				url: '/swagger/swagger.json',
				dom_id: '#swagger-ui'
			})
		</script>
	</body>
</html>`
		return c.Type("html").SendString(html)
	})
	routes.RouterUser(app)
	routes.RouterAdmin(app)
	// Start the server using port from config
	if config.AppConfig != nil && config.AppConfig.Port != "" {
		if err := app.Listen(":" + config.AppConfig.Port); err != nil {
			config.Logger.Sugar().Fatalf("Server başlatılamadı: %v", err)
		}
	} else {
		if err := app.Listen(":8080"); err != nil {
			config.Logger.Sugar().Fatalf("Server başlatılamadı: %v", err)
		}
	}
}
