package voice

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 GetVoiceWebToken(c *fiber.Ctx) error {
	voiceWebCode := c.Params("voiceWebCode")

	// get uuid from player by voiceWebCode

	var f Fields

	err := mongo.PlayersCollection.FindOne(context.TODO(), bson.D{{"voiceWebCode", voiceWebCode}}).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
	voiceSessionToken, err := util.GenerateRandomString(64)

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

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

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

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

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

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

	// delete web code

	/*delRes, err := mongo.PlayerRegistrationProcessCollection.DeleteOne(context.TODO(), bson.D{{"voiceWebCode", voiceWebCode}})

	if err != nil {
		logger.WebVoice.Infoln("del err", err)
	}

	logger.WebVoice.Infoln("resa", delRes.DeletedCount)

	// generate mobile code for qrcode and manual code insert
	/*mobileCode, err := util.GenerateRandomNumbers(12)

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

	// update mobile code in collection
	filter = bson.D{{"uuid", f.Uuid}}
	update = bson.D{{"$set", bson.D{{"mobileCode", mobileCode}}}, {"$unset", bson.D{{"voiceWebCode", ""}}}}

	res, err = mongo.PlayerRegistrationProcessCollection.UpdateOne(context.TODO(), filter, update)

	if err != nil {
		logger.WebVoice.Infoln("err", err)
	} */

	// delete player from player registration process collection

	return c.SendStatus(fiber.StatusOK)
}
