package main

import (
	"log"
	uyar_app_main "server/apps/uyar_dokum/uyar_ana"

	FikoYTCtx "server/sistem/fikoyt_ctx"
	fiko_socket_io "server/sistem/fikoyt_socket_io"
	"server/sistem/kok"

	"github.com/gofiber/fiber/v3"
)

func main() {
	app := fiber.New(fiber.Config{AppName: "FikoYT Sunucu", ErrorHandler: GlobalErrorHandler, StreamRequestBody: true, Immutable: true, BodyLimit: 4000 * 1024 * 1024})

	FikoYTCtx.Ayarla(app)
	// app.Use(logger.New())
	// FikoYTCevap.Ayarla(app)
	// app.Use(requestid.New())
	// app.Use(recoverer.New())
	// app.Use(fikoyt_json.AraIsleyici())
	// app.Use(FikoYTDosya.AraIsleyici())
	// Mogodb İnit Ediliyor
	// fiko_mongo.Init(app)
	/**/
	fiko_socket_io.Ayarla(app)
	uyar_app_main.Ayarla(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")
}
