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/socketclients"

	"git.ex.umbach.dev/Alex/roese-utils/rslogger"
	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

func SignOutSession(c *fiber.Ctx) error {
	// swagger:operation DELETE /user/session/{idForDeletion} user userSignOutSession
	// ---
	// summary: Sign out user session
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: X-Api-Key
	//   in: header
	//   description: You can create a new api key in your user profile
	// - name: idForDeletion
	//   in: path
	//   description: Id for deletion
	// responses:
	//   '200':
	//     description: User session signed out successfully
	//   '400':
	//     description: Invalid request body
	//   '401':
	//     description: No permissions
	//   '500':
	//     description: Failed to sign out user session

	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(rslogger.LogTypeInfo, "User %s has logged out one of his account sessions", c.Locals("userId").(string))
	}

	return c.JSON(fiber.Map{"status": "ok"})
}
