package team

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

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

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

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

	c.JSON(http.StatusOK, teams)
	// if len(teams) > 0 {
	// 	return
	// }

	// common.RespondMessage(c, "No Players found")
}

func CreateTeam(c *gin.Context, db *sql.DB) {
	var team Team
	if err := c.ShouldBindJSON(&team); err != nil {
		common.RespondError(c, http.StatusBadRequest, "Invalid request payload")
		return
	}

	err := saveTeam(db, team)
	if err != nil {
		log.Printf("Error saving team: %v", err)
		common.RespondError(c, http.StatusBadRequest, "Error saving Team")
	}
	common.RespondSuccess(c, http.StatusOK)
}

func UpdateTeam(c *gin.Context, db *sql.DB) {
	log.Println("team id: ", c.Param("uuid"))
	var team Team
	if err := c.ShouldBindJSON(&team); err != nil {
		common.RespondError(c, http.StatusBadRequest, "Error updating Team; Could not bind Params")
		return
	}
	team.UUID = c.Param("uuid")
	err := updateTeam(db, team)
	if err != nil {
		log.Printf("Error updating team: %v", err)
		common.RespondError(c, http.StatusBadRequest, "Error updating Team")
	}
	common.RespondSuccess(c, http.StatusOK)

}
