package user

import (
	"fmt"
	"jannex/admin-dashboard-backend/modules/config"
	"jannex/admin-dashboard-backend/modules/database"
	"jannex/admin-dashboard-backend/modules/logger"
	"jannex/admin-dashboard-backend/modules/structs"
	"jannex/admin-dashboard-backend/modules/utils"
	"jannex/admin-dashboard-backend/socketclients"
	"os"
	"strings"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
	"github.com/savsgio/gotils/uuid"
)

func UpdateAvatar(c *fiber.Ctx) error {
	fileHeader, err := c.FormFile("file")

	if err != nil {
		log.Error().Msgf("User Avatar file error: %v", err)
		return c.SendStatus(fiber.StatusBadRequest)
	}

	if fileHeader.Size > utils.MaxAvatarSize {
		return c.SendStatus(fiber.StatusRequestEntityTooLarge)
	}

	if !isAvatarFileTypeInList(fileHeader.Header["Content-Type"][0]) {
		return c.SendStatus(fiber.StatusUnprocessableEntity)
	}

	user := structs.User{Id: c.Locals("userId").(string)}

	database.DB.First(&user)

	if user.Avatar != "" {
		os.Remove(config.Cfg.FolderPaths.PublicStatic + "avatars/" + user.Avatar)
	}

	fileName := uuid.V4() + "." + strings.Split(fileHeader.Header["Content-Type"][0], "/")[1]

	database.DB.Model(&structs.User{}).Where("id = ?", user.Id).Updates(&structs.User{Avatar: fileName})

	socketclients.BroadcastMessage(structs.SendSocketMessage{
		Cmd: utils.SentCmdUpdateAllUsersUserAvatar,
		Body: struct {
			UserId string
			Avatar string
		}{
			UserId: user.Id,
			Avatar: fileName,
		},
	})

	logger.AddSystemLog(structs.LogMessage{
		Id:   21,
		Type: utils.LogTypeInfo,
		Messages: []structs.LogData{
			{Type: "userId", Value: user.Id},
		},
	})

	return c.SaveFile(fileHeader, fmt.Sprintf("%savatars/%s", config.Cfg.FolderPaths.PublicStatic, fileName))
}

func isAvatarFileTypeInList(contentType string) bool {
	for _, aType := range utils.AcceptedAvatarFileTypes {
		if aType == contentType {
			return true
		}
	}

	return false
}
