package mobile

import (
	"context"
	"time"

	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/bson"
	"krakatoa.net/backend/modules/logger"
	"krakatoa.net/backend/modules/mongo"
	"krakatoa.net/backend/modules/util"
)

type Fields struct {
	Uuid string
}

func GetMobileWebToken(c *fiber.Ctx) error {
	mobileWebCode := c.Params("mobileWebCode")

	logger.WebMobile.Infoln("mobileWebCode", mobileWebCode)

	// get uuid from player by mobileWebCode

	var f Fields

	err := mongo.PlayersCollection.FindOne(context.TODO(), bson.D{{"mobileWebCode", mobileWebCode}}).Decode(&f)

	if err != nil {
		logger.Mongo.Println("err", err)
		return c.SendStatus(fiber.StatusUnauthorized)
	}

	// create token for voice web socket and send as cookie
	mobileSessionToken, err := util.GenerateRandomString(64)

	if err != nil {
		logger.WebMobile.Println("err", err)
	}

	c.Cookie(&fiber.Cookie{Name: "token", Value: mobileSessionToken, HTTPOnly: true, Secure: true, Expires: time.Now().Add(time.Hour * 24 * 7)})

	// set mobile web socket token to player in player collection

	filter := bson.D{{"uuid", f.Uuid}}
	update := bson.M{"$set": bson.M{"mobileSessionToken": mobileSessionToken}, "$unset": bson.M{"mobileWebCode": ""}}

	_, err = mongo.PlayersCollection.UpdateOne(context.TODO(), filter, update)

	if err != nil {
		logger.WebMobile.Println("err1", err)
	}

	return c.SendStatus(fiber.StatusOK)
}
