package main

import (
	"log"
	uyar_app_main "server/apps/uyar_casting/uyar_main"
	"server/kok"
	FikoYTResponse "server/sistem/fikoyt_cevap"
	FikoYTFile "server/sistem/fikoyt_file"
	"server/sistem/fikoyt_json"
	fiko_mongo "server/sistem/fikoyt_mongo"
	fiko_socket_io "server/sistem/fikoyt_socket_io"

	"github.com/gofiber/fiber/v3"
	recoverer "github.com/gofiber/fiber/v3/middleware/recover"
	"github.com/gofiber/fiber/v3/middleware/requestid"
)

func main() {
	app := fiber.New(fiber.Config{AppName: "FikoYT Sunucu", ErrorHandler: GlobalErrorHandler, StreamRequestBody: true, Immutable: true, BodyLimit: 4000 * 1024 * 1024})
	// app.Use(logger.New())
	FikoYTResponse.Init(app)
	app.Use(requestid.New())
	app.Use(recoverer.New())
	app.Use(fikoyt_json.Yeni())
	app.Use(FikoYTFile.FileHandlerMiddleware)
	// Mogodb İnit Ediliyor
	fiko_mongo.Init(app)
	/**/
	fiko_socket_io.Init(app)
	uyar_app_main.Init(app)
	//
	kok.KokRouting(app)

	runSslWithPrefork(app)
}

func runSslWithPrefork(app *fiber.App) {
	// SSL sertifikası yükleniyor
	// cert, err := tls.LoadX509KeyPair("cert/server.crt", "cert/server.key")
	// if err != nil {
	// 	log.Fatalf("SSL Sertifikası yüklenirken hata oluştu: %v", err)
	// }

	// TLS yapılandırması
	// tlsConfig := &tls.Config{
	// 	Certificates: []tls.Certificate{cert},
	// }

	// ListenConfig kullanılarak sunucu başlatılıyor
	app.Listen(":3000", fiber.ListenConfig{
		CertFile:    "cert/server.crt",
		CertKeyFile: "cert/server.key",

		// TLSConfigFunc:         tlsConfig, // SSL yapılandırması
		EnablePrefork:     true, // Prefork etkinleştiriliyor
		EnablePrintRoutes: true, // Rotalar yazdırılsın
	})
}

// func runSsl(app *fiber.App) {
// 	// Create tls certificate
// 	cer, err := tls.LoadX509KeyPair("cert/server.crt", "cert/server.key")
// 	if err != nil {
// 		log.Fatal(err)
// 	}
// 	config := &tls.Config{Certificates: []tls.Certificate{cer}}
// 	// Create custom listener
// 	ln, err := tls.Listen("tcp", ":3000", config)
// 	if err != nil {
// 		panic(err)
// 	}

// 	// Start server with https/ssl enabled on http://localhost:443
// 	log.Fatal(app.Listener(ln, fiber.ListenConfig{EnablePrefork: true, EnablePrintRoutes: true}))
// }

func GlobalErrorHandler(c fiber.Ctx, err error) error {
	if err == nil {
		return c.Status(fiber.StatusInternalServerError).SendString("An unknown error occurred")
	}

	// Fiber özel hatalarını yönet
	if e, ok := err.(*fiber.Error); ok {
		return c.Status(e.Code).SendString(e.Message)
	}

	// Genel hatalar için
	log.Printf("Unhandled error: %v", err)
	return c.Status(fiber.StatusInternalServerError).SendString("Internal server error")
}
