package main

import (
	"fmt"
	"log"
	"os"
	"time"
	"volleyball/internal/auth"
	"volleyball/internal/database"
	"volleyball/internal/player"
	"volleyball/internal/team"
	"volleyball/internal/tournament"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

/**
* @brief Main function to start the server
 */
func main() {

	var host = "localhost"
	var DBport = 5432
	var user = "volleyball"

	db := database.New(host, DBport, user, "volleyball", "volleyball")
	db.Connect()

	// Setup the database and tables
	if err := db.SetupTables(); err != nil {
		os.Exit(1)
	}

	router := gin.Default()
	// 2. CORS-Konfiguration
	// Lese die Frontend-URL aus den Umgebungsvariablen
	frontendURL := os.Getenv("FRONTEND_URL")

	// Lokaler Fallback (wichtig für die Entwicklung)
	allowedOrigins := []string{
		"http://localhost:3000", // Gängiger React-Dev-Port
		// "http://localhost:5173", // Gängiger Vite-Dev-Port
	}

	if frontendURL != "" {
		allowedOrigins = append(allowedOrigins, frontendURL)
		fmt.Printf("CORS: Erlaubte Produktiv-URL hinzugefügt: %s\n", frontendURL)
	} else {
		log.Println("ACHTUNG: FRONTEND_URL fehlt in den Umgebungsvariablen. Nur lokale URLs erlaubt.")
	}

	// CORS
	// Konfiguriere die CORS-Middleware
	config := cors.Config{
		// Setze die erlaubten Ursprünge (deine React-URLs)
		AllowOrigins: allowedOrigins,
		// Erlaube die notwendigen HTTP-Methoden
		AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
		// Erlaube Header (z.B. für JSON und Authentifizierung)
		AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
		// Erlaube Cookies und Credentials (falls du Tokens oder Sessions nutzt)
		AllowCredentials: true,
		// Wie lange die Preflight-Anfrage (OPTIONS) gecacht werden darf
		MaxAge: 12 * time.Hour,
	}
	router.Use(cors.New(config))

	// Public
	router.POST("/api/login", func(c *gin.Context) {
		auth.LoginHandler(c, db.GetDB())
	})

	router.GET("/api/tournaments", tournament.ListTournaments)

	// Protected API
	api := router.Group("/api")
	api.Use(auth.AuthMiddleware())

	api.GET("/tournaments/:id", tournament.GetTournament)
	api.POST("/tournaments/:id/join", tournament.JoinTournament)
	api.PUT("/tournaments/:id", tournament.UpdateTournament)

	// api.GET("/players", func(c *gin.Context) {
	// 	player.GetPlayers(c, db.GetDB())
	// })
	api.GET("/players", auth.AuthorizeJWT("admin"), func(c *gin.Context) { player.GetPlayers(c, db.GetDB()) })

	api.GET("/players/:id", func(c *gin.Context) {
		player.GetPlayer(c, db.GetDB(), c.Param("id"))
	})
	api.POST("/players", func(c *gin.Context) {
		player.CreatePlayer(c, db.GetDB())
	})
	api.PUT("/players/:id", func(c *gin.Context) {
		log.Println("PUT /players/:id called", c.Params)
		player.UpdatePlayer(c, db.GetDB())
	})
	api.DELETE("/players/:id", func(c *gin.Context) {
		player.DeletePlayer(c, db.GetDB())
		// c.JSON(http.StatusOK, gin.H{"message": "Player deleted successfully"})
	})
	api.GET("/teams", func(c *gin.Context) {
		log.Println("get Teams called")
		team.GetTeams(c, db.GetDB())
	})

	api.POST("/teams", func(c *gin.Context) {
		log.Println("create teams called")
		team.CreateTeam(c, db.GetDB())
	})
	api.PUT("/teams/:uuid", func(c *gin.Context) {
		log.Println("update teams called")
		team.UpdateTeam(c, db.GetDB())
	})
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	router.Run(":" + port)
}
