package controllers

import (
	"fmt"
	"strconv"

	"gitea.tbdevent.eu/TBD/reforger_crawler_main/initializers"
	"gitea.tbdevent.eu/TBD/reforger_crawler_main/models"
	"github.com/gin-gonic/gin"
)

func CreateAddon(c *gin.Context) {
	var addonR models.Addon
	body := make([]byte, 0)
	c.Request.Body.Read(body)
	fmt.Println(body)
	err := c.ShouldBindJSON(&addonR)
	if err != nil {
		c.JSON(400, gin.H{"error": "Invalid JSON"})
		return
	}

	addon := models.Addon{
		ID:                   addonR.ID,
	}

	result := initializers.DB.Where(&addon).First(&addon)
	if result.Error != nil {
		// addon does not exist, create it
		initializers.DB.Create(&addonR)
	} else {
		// addon exists, check version, update it and queue for reindexing if needed
		if addon.CurrentVersionNumber != addonR.CurrentVersionNumber {
			addon.CurrentVersionNumber = addonR.CurrentVersionNumber
			addon.CurrentVersionID = addonR.CurrentVersionID
			addon.CurrentVersionSize = addonR.CurrentVersionSize
			addon.ToBeIndexed = true
			initializers.DB.Save(&addon)
		}		
	}
	c.JSON(200, gin.H{"status": "success"})
}
func GetCurrentState(c *gin.Context) {
	offsetStr := c.Query("offset")
	limitStr := c.Query("limit")

	offset := 0
	limit := 0
	if offsetStr != "" {
		if val, err := strconv.Atoi(offsetStr); err == nil {
			offset = val
		}
	}
	if limitStr != "" {
		if val, err := strconv.Atoi(limitStr); err == nil {
			limit = val
		}
	}

	var addons []models.Addon
	initializers.DB.Limit(limit).Offset(offset).Find(&addons)

	c.JSON(200, addons)
}
