package controllers

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"gitlab.com/pactual1/backend/models"
	"gitlab.com/pactual1/backend/shared"
)

func ListProductTemplates(c *gin.Context) {
	// Get limit and offset from query parameter with defaults
	limitStr := c.DefaultQuery("limit", "99999999999999999999999999999999")
	offsetStr := c.DefaultQuery("offset", "0")

	// Convert limit and offset to int
	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		log.Printf("ListProductTemplates Error: Invalid limit value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid limit value"})
		return
	}

	offset, err := strconv.Atoi(offsetStr)
	if err != nil {
		log.Printf("ListProductTemplates Error: Invalid offset value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid offset value"})
		return
	}

	// Create a slice to hold the product templates
	var productTemplates []models.ProductTemplate

	// Count the total number of product templates
	var total int64
	if err := shared.GetDb().Model(&models.ProductTemplate{}).Count(&total).Error; err != nil {
		log.Printf("ListProductTemplates Error: Database error: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
		return
	}

	// Fetch the product templates from the database with LIMIT and OFFSET
	if err := shared.GetDb().Order("created_at desc").Limit(limit).Offset(offset).Find(&productTemplates).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			log.Printf("ListProductTemplates Error: No product templates found: %v", err)
			c.JSON(http.StatusNotFound, gin.H{"error": "No product templates found"})
		} else {
			log.Printf("ListProductTemplates Error: Database error: %v", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"})
		}
		return
	}

	// Respond with the product templates and the total count
	c.JSON(http.StatusOK, gin.H{"total": total, "product_templates": productTemplates})
}

func GetProductTemplate(c *gin.Context) {
	// Get the product template ID from query parameters
	productTemplateIDStr := c.Param("template_id")

	if productTemplateIDStr == "" {
		log.Printf("GetProductTemplate Error: Product Template ID is required")
		c.JSON(http.StatusBadRequest, gin.H{"error": "Product Template ID is required"})
		return
	}

	productTemplateID, err := strconv.ParseUint(productTemplateIDStr, 10, 32)
	if err != nil {
		log.Printf("GetProductTemplate Error: Invalid Product Template ID: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Product Template ID"})
		return
	}

	// Fetch the product template
	var productTemplate models.ProductTemplate
	if err := shared.GetDb().Where("id = ?", productTemplateID).First(&productTemplate).Error; err != nil {
		log.Printf("GetProductTemplate Error: Could not fetch product template: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not fetch product template"})
		return
	}

	err = json.Unmarshal([]byte(productTemplate.Config), &productTemplate.ProductTemplateConfig)
	if err != nil {
		log.Printf("GetProductTemplate Error: Could not fetch product template config: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not fetch product template config"})
		return
	}
	// Respond with the product template
	c.JSON(http.StatusOK, productTemplate)
}
