package user

import (
	"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"

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

func SignOutSession(c *fiber.Ctx) error {
	var params structs.UserSignOutSessionRequest

	if err := c.ParamsParser(&params); err != nil {
		log.Error().Msg("Failed to parse params, err: " + err.Error())
		return c.SendStatus(fiber.StatusBadRequest)
	}

	var userSession structs.UserSession

	database.DB.First(&userSession, "id_for_deletion = ?", params.IdForDeletion)

	if userSession.Id != "" {
		database.DB.Delete(&structs.UserSession{}, "id = ?", userSession.Id)

		socketclients.CloseAllUserSessionConnections(userSession.Id)

		socketclients.UpdateUserSessionsForUser(userSession.UserId, userSession.Id)

		logger.AddSystemLog(structs.LogMessage{
			Id:   22,
			Type: utils.LogTypeInfo,
			Messages: []structs.LogData{
				{
					Type:  "userId",
					Value: c.Locals("userId").(string),
				},
			},
		})
	}

	return c.SendStatus(fiber.StatusOK)
}
