package user

import (
	"time"

	"git.umbach.dev/app-idea/rest-api/modules/database"
	"git.umbach.dev/app-idea/rest-api/modules/structs"
	"github.com/gofiber/fiber/v2"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func createUserAction(userId string) (string, error) {
	userActionId, err := generateRandomString(16, 1)

	if err != nil {
		log.Warnln("Failed to generate random string")
		return "", err
	}

	db := database.DB

	db.Create(structs.UserAction{Id: userActionId, UserId: userId, Expires: getUserActionExpiresTime(cfg.Settings.Expires.UserActions.Id_0)})

	log.Infoln("createAction", cfg.Settings.Expires.UserActions.Id_0)

	return userActionId, nil
}

func deleteExpiredUserActions(db *gorm.DB) {
	var res string

	db.Raw("DELETE FROM user_actions WHERE expires < ?", time.Now()).Scan(&res)
}

func HandleActions(c *fiber.Ctx) error {
	log.Infoln("handleActions", c.Params("actionType"), c.Params("actionId"))

	//actionType, _ := strconv.ParseInt(c.Params("actionType"), 10, 64)

	switch c.Params("actionType") {
	case "0":
		return ActivateUser(c)
	case "1":
		return deleteUser(c)
	default:
		log.Info("ActionId not found")
		return c.SendStatus(fiber.StatusInternalServerError)
	}
}

func getUserActionExpiresTime(actionTime int) time.Time {
	return time.Now().Add(time.Minute * time.Duration(actionTime))
}
