package verifycode

import (
	"jannex/telegram-bot-manager/modules/cache"
	"jannex/telegram-bot-manager/modules/database"
	"jannex/telegram-bot-manager/modules/logger"
	"jannex/telegram-bot-manager/modules/structs"
	"jannex/telegram-bot-manager/modules/utils"
	"time"

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

func GetVerifyCode(c *fiber.Ctx) error {
	// swagger:operation GET /v1/verifycode/{userId} verifycode getVerifyCode
	// ---
	// summary: Get verify code for user
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: userId
	//   in: params
	//   description: User ID
	//   required: true
	//   type: string
	// responses:
	//   '200':
	//     description: OK
	//     schema:
	//       "$ref": "#/definitions/VerifyCodeResponse"
	//   '400':
	//     description: Bad request
	//   '500':
	//     description: Internal server error

	var params structs.UserIdParam

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

	code, err := rsutils.GenerateCode(6)

	if err != nil {
		return c.SendStatus(fiber.StatusInternalServerError)
	}

	cache.AddTempVerifyCode(structs.TempVerifyCode{
		UserId:    params.UserId,
		Code:      code,
		ExpiredAt: time.Now().Add(utils.TempVerifyCodeExpirationTime),
	})

	logger.AddSystemLog(rslogger.LogTypeInfo, "Generated verify code for user %s", params.UserId)

	return c.JSON(structs.VerifyCodeResponse{Code: code})
}

func DeleteVerifiedUser(c *fiber.Ctx) error {
	// swagger:operation DELETE /v1/verifycode/{userId} verifycode deleteVerifiedUser
	// ---
	// summary: Delete verified user
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: userId
	//   in: params
	//   description: User ID
	//   required: true
	//   type: string
	// responses:
	//   '200':
	//     description: OK
	//   '400':
	//     description: Bad request
	//   '500':
	//     description: Internal server error

	var params structs.UserIdParam

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

	res := database.DB.Where("user_id = ?", params.UserId).Delete(&structs.VerifiedUser{})

	if res.RowsAffected == 0 {
		logger.AddSystemLog(rslogger.LogTypeInfo, "Requested to delete verified user %s, but user not found", params.UserId)
	} else {
		logger.AddSystemLog(rslogger.LogTypeInfo, "Deleted verified user %s", params.UserId)
	}

	return c.SendStatus(fiber.StatusOK)
}
