package users

import (
	db "ttime/internal/database"
	"ttime/internal/types"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
	"github.com/golang-jwt/jwt/v5"
)

// ChangeUserName changes a user's username in the database
func ChangeUserName(c *fiber.Ctx) error {
	// Check token and get username of current user
	user := c.Locals("user").(*jwt.Token)
	claims := user.Claims.(jwt.MapClaims)
	adminUsername := claims["name"].(string)
	log.Info(adminUsername)

	// Extract the necessary parameters from the request
	data := new(types.StrNameChange)
	if err := c.BodyParser(data); err != nil {
		log.Info("Error parsing username")
		return c.Status(400).SendString(err.Error())
	}

	// Check if the current user is an admin
	isAdmin, err := db.GetDb(c).IsSiteAdmin(adminUsername)
	if err != nil {
		log.Warn("Error checking if admin:", err)
		return c.Status(500).SendString(err.Error())
	} else if !isAdmin {
		log.Warn("Tried changing name when not admin")
		return c.Status(401).SendString("You cannot change name unless you are an admin")
	}

	// Change the user's name in the database
	if err := db.GetDb(c).ChangeUserName(data.PrevName, data.NewName); err != nil {
		return c.Status(500).SendString(err.Error())
	}

	// Return a success message
	return c.SendStatus(fiber.StatusOK)
}