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 ListTextTemplates(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("ListTextTemplates 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("ListTextTemplates Error: Invalid offset value: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid offset value"})
		return
	}

	// Create a slice to hold the text templates
	var textTemplates []models.TextTemplate

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

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

	// Respond with the text templates and the total count
	c.JSON(http.StatusOK, gin.H{"total": total, "text_templates": textTemplates})
}

func CreateTextTemplate(c *gin.Context) {
	var textTemplate models.TextTemplate
	rawData, _ := c.GetRawData()

	// Unmarshal to the important info structure
	err := json.Unmarshal(rawData, &textTemplate)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON payload"})
		log.Printf("Invalid json pyload : %v", err)
		return
	}

	// Save text template to your database
	if err := shared.GetDb().Create(&textTemplate).Error; err != nil {
		log.Printf("CreateTextTemplate DB Error: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not create text template"})
		return
	}

	log.Printf("Successfully received and saved text template: %v", textTemplate)
	c.JSON(http.StatusOK, gin.H{"data": textTemplate})
}

