package permitjoin

import (
	"jannex/robot-control-manager/modules/cache"
	"jannex/robot-control-manager/modules/logger"
	"jannex/robot-control-manager/modules/robot"
	"jannex/robot-control-manager/modules/structs"
	"jannex/robot-control-manager/modules/utils"

	"git.ex.umbach.dev/Alex/roese-utils/rsutils"
	"github.com/gofiber/fiber/v2"
)

func SetPermitJoin(c *fiber.Ctx) error {
	// swagger:operation POST /permitjoin/{enabled} permitjoin setPermitJoin
	// ---
	// summary: Set permit join.
	// description: |
	//   This is used to enable or disable permit join.
	// parameters:
	// - in: path
	//   name: enabled
	//   description: Enable or disable permit join. 0 = disable, 1 = enable.
	//   required: true
	//   schema:
	//     type: integer
	//     enum: [0, 1]
	// responses:
	//   "200":
	//    description: Permit join set
	//   "400":
	//    description: Invalid request body

	var params structs.PermitJoinParam

	if err := rsutils.ParamsParserHelper(c, &params); err != nil {
		return c.SendStatus(fiber.StatusBadRequest)
	}

	if params.Enabled == 0 {
		cache.SetPermitJoin(false)
		logger.AddSystemLog("Permit join disabled")

		if robot.PermitJoinTimer != nil {
			robot.PermitJoinTimer.Stop()
		}
	} else {
		cache.SetPermitJoin(true)
		logger.AddSystemLog("Permit join enabled")

		go robot.PermitJoinAutoDisableHandler()
	}

	robot.BroadcastSSEMessage(structs.SSEMessage{
		Cmd:  utils.SSESentCmdPermitJoinUpdated,
		Body: params.Enabled == 1,
	})

	return c.SendStatus(fiber.StatusOK)
}

func GetPermitJoin(c *fiber.Ctx) error {
	// swagger:operation GET /permitjoin permitjoin getPermitJoin
	// ---
	// summary: Get permit join.
	// description: |
	//   This is used to get the current permit join status.
	// produces:
	// - application/json
	// responses:
	//   "200":
	//    description: Permit join status
	//    schema:
	//     "$ref": "#/definitions/PermitJoinResponse"

	return c.JSON(structs.PermitJoinResponse{
		Enabled: cache.GetPermitJoin(),
	})
}
