package controllers

import (
	"cds/dao"
	"cds/models"
	"fmt"

	"github.com/gofiber/fiber/v2"
	"go.mongodb.org/mongo-driver/mongo"
)

// @Summary Renvoie les informations sur un jeu.
// @Produce json
// @Success 200 {object} models.Game
// @Failure 403
// @Failure 404
// @Failure 500
// @Router /games/{id} [get]
func GetGameById(c *fiber.Ctx) error {
	token := c.Cookies("token", "")
	if token == "" {
		return c.SendStatus(fiber.StatusForbidden)
	} else {
		id := c.Params("id")
		game, err := dao.GetGameById(id)
		if err == mongo.ErrNoDocuments {
			return c.SendStatus(fiber.StatusNotFound)
		} else if err != nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"error": fmt.Sprint(err),
			})
		} else {
			return c.Status(fiber.StatusOK).JSON(game)
		}
	}
}

// @Summary Renvoie une liste de 10 jeux dont le nom contient la requĂȘte.
// @Produce json
// @Success 200 {object} List models.Game
// @Failure 403
// @Failure 500
// @Router /games/search?name={name} [get]
func FindGame(c *fiber.Ctx) error {
	token := c.Cookies("token", "")
	if token == "" {
		return c.SendStatus(fiber.StatusForbidden)
	} else {
		name := c.Query("name", "")
		games, err := dao.SearchSimilarNames(name)
		if err != nil {
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"error": fmt.Sprint(err),
			})
		} else {
			res := []models.Game{}
			for e := games.Front(); e != nil; e = e.Next() {
				res = append(res, e.Value.(models.Game))
			}

			return c.Status(fiber.StatusOK).JSON(res)
		}
	}
}