package logger

import (
	"jannex/admin-dashboard-backend/modules/cache"
	"jannex/admin-dashboard-backend/modules/grouptasks"
	"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"
)

func GetSystemLog(c *fiber.Ctx) error {
	t := c.Query("type")
	date := c.Query("date")
	lang := c.Query("lang")

	if t == "" || date == "" || lang == "" {
		return c.SendStatus(fiber.StatusBadRequest)
	}

	if t == "g" && !socketclients.HasPermission(c.Locals("userId").(string), utils.PermissionGroupTasksHistory) || t == "s" && !socketclients.HasPermission(c.Locals("userId").(string), utils.PermissionAdminAreaLogs) {
		return c.SendStatus(fiber.StatusUnauthorized)
	}

	logType := "Group Tasks"

	if t == "s" {
		logType = "System"
	}

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

	// / TODO: remove this by rendering the log message on backend site

	if t == "g" {
		// grouptasks logs
		return c.JSON(structs.LogMessageResponse{
			Logs:            logger.ReadLogs(date, false, lang),
			Dates:           logger.GetAllLogMessagesDates(false),
			Users:           socketclients.GetAllUsers(),
			Roles:           socketclients.GetAllRoles(),
			CategoryGroups:  cache.GetCategoryGroupsSorted(),
			GroupTasks:      grouptasks.GetAllGroupTasks(),
			GroupTasksSteps: grouptasks.GetAllGroupTasksSteps(),
		})
	}

	// system logs
	return c.JSON(structs.LogMessageResponse{
		Logs:            logger.ReadLogs(date, true, lang),
		Dates:           logger.GetAllLogMessagesDates(true),
		Users:           socketclients.GetAllUsers(),
		Roles:           socketclients.GetAllRoles(),
		CategoryGroups:  cache.GetCategoryGroupsSorted(),
		GroupTasks:      grouptasks.GetAllGroupTasks(),
		GroupTasksSteps: grouptasks.GetAllGroupTasksSteps(),
	})
}
