package player

import (
	"database/sql"
	"log"
	"net/http"
	"volleyball/internal/common"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func GetPlayers(c *gin.Context, db *sql.DB) {
	// log.Println(c.)
	log.Println(c.GetString("userId"), c.GetString("email"), c.GetString("role"))
	// Simulate fetching players from a database

	players, err := GetAllPlayers(db)
	if err != nil {
		log.Printf("Error retrieving players: %v", err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to retrieve players")
		return
	}

	if len(players) > 0 {
		log.Printf("User %s (%s) requested players", c.GetString("userId"), c.GetString("email"))
		c.JSON(http.StatusOK, players)
		return
	}
	log.Printf("User %s (%s) requested players, but none found", c.GetString("userId"), c.GetString("email"))

	common.RespondError(c, http.StatusNotFound, "No Players found")
}

func CreatePlayer(c *gin.Context, db *sql.DB) {
	log.Println("CreatePlayer called")
	var newPlayer User
	var err error
	if err := c.ShouldBindJSON(&newPlayer); err != nil {
		log.Printf("Error binding player data: %v", err)
		common.RespondError(c, http.StatusBadRequest, "Invalid player data")
		return
	}
	newPlayer.password, err = common.HashPassword(newPlayer.password)
	if err != nil {
		log.Printf("Error hashing password: %v", err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to hash password")
		return
	}

	newPlayer.UUID = uuid.New().String()
	err = savePlayer(db, newPlayer)
	if err != nil {
		log.Printf("Error saving player: %v", err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to create player")
		return
	}
	var roles = []string{"player"}
	err = AddRoleToPlayer(db, newPlayer.UUID, roles)
	if err != nil {
		log.Printf("Error adding role to player: %v", err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to assign role to player")
		return
	}

	log.Printf("User %s (%s) created player: %s", c.GetString("userId"), c.GetString("email"), newPlayer.Username)

	common.RespondCreated(c, newPlayer)
}

func GetPlayer(c *gin.Context, db *sql.DB, id string) {
	log.Println("GetPlayer called with ID:", id)
	playerID := c.Param("id")
	if playerID == "" {
		common.RespondError(c, http.StatusBadRequest, "Player ID is required")
		return
	}

	player, err := GetPlayerByID(db, playerID)
	if err != nil {
		log.Printf("Error retrieving player with ID %s: %v", playerID, err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to retrieve player")
		return
	}

	if player.UUID == "" {
		log.Printf("Player with ID %s not found", playerID)
		common.RespondError(c, http.StatusNotFound, "Player not found")
		return
	}
	role, err := GetPlayerRole(db, player.UUID)
	if err != nil {
		log.Printf("Error retrieving role for player ID %s: %v", player.UUID, err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to retrieve player role")
		return
	}
	player.Role = role
	log.Printf(player.UUID, player.Username, player.Email, player.Role)
	c.JSON(http.StatusOK, player)

}

func UpdatePlayer(c *gin.Context, db *sql.DB) {
	log.Println(c)
	playerID := c.Param("id")
	if playerID == "" {
		common.RespondError(c, http.StatusBadRequest, "Player ID is required")
		return
	}
	log.Println("role: ", c.GetString("role"))
	// playerID != c.GetString("userId") ||
	if c.GetString("role") != "admin" {
		common.RespondError(c, http.StatusForbidden, "You do not have permission to update this player")
		return
	}

	var updatedPlayer User
	if err := c.ShouldBindJSON(&updatedPlayer); err != nil {
		log.Printf("Error binding player data: %v", err)
		common.RespondError(c, http.StatusBadRequest, "Invalid player data")
		return
	}

	updatedPlayer.UUID = playerID
	err := updatePlayer(db, updatedPlayer)
	if err != nil {
		log.Printf("Error updating player with ID %s: %v", playerID, err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to update player")
		return
	}

	log.Printf("User %s (%s) updated player: %s", c.GetString("userId"), c.GetString("email"), updatedPlayer.Username)

	c.JSON(http.StatusOK, updatedPlayer)
}
func DeletePlayer(c *gin.Context, db *sql.DB) {
	playerID := c.Param("id")
	if playerID == "" {
		common.RespondError(c, http.StatusBadRequest, "Player ID is required")
		return
	}
	if c.GetString("role") != "admin" {
		common.RespondError(c, http.StatusForbidden, "You do not have permission to delete this player")
		return
	}

	err := deletePlayer(db, playerID)
	if err != nil {
		log.Printf("Error deleting player with ID %s: %v", playerID, err)
		common.RespondError(c, http.StatusInternalServerError, "Failed to delete player")
		return
	}

	log.Printf("User %s (%s) deleted player with ID: %s", c.GetString("userId"), c.GetString("email"), playerID)

	c.JSON(http.StatusOK, gin.H{"message": "Player deleted successfully"})
	// common.RespondSuccess(c, "Player deleted successfully")
}
