package carddeck

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"spahl.ddns.net/jasper/wok-able-backend/auth"
	"spahl.ddns.net/jasper/wok-able-backend/models"
)

func getCardDecks(c *gin.Context) {
	var cardDecks []models.CardDeck
	models.DB.Scopes(auth.UserScope(c)).Preload("Cards").Find(&cardDecks)
	dto := []models.CardDeckDto{}
	for _, deck := range cardDecks {
		dto = append(dto, deck.ToDto())
	}
	c.IndentedJSON(http.StatusOK, dto)
}

func getCardDeckById(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.Status(http.StatusBadRequest)
		return
	}
	var cardDeck models.CardDeck
	err = models.DB.Scopes(auth.UserScope(c)).Preload("Cards").First(&cardDeck, id).Error
	if err != nil {
		c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Card Deck not found"})
		return
	}
	c.IndentedJSON(http.StatusOK, cardDeck.ToDto())
}

func createCardDeck(c *gin.Context) {
	var cardDeck models.CardDeck
	if err := c.BindJSON(&cardDeck); err != nil {
		return
	}
	cardDeck.UserID = uint(c.GetFloat64("user_id"))

	if models.DB.Scopes(auth.UserScope(c)).Create(&cardDeck).Save(&cardDeck).Error != nil {
		return
	}
	c.IndentedJSON(http.StatusCreated, cardDeck)
}
