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", "50")
	offsetStr := c.DefaultQuery("offset", "0")
	iDsStr := c.QueryArray("ids[]")

	// 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
	}

	// Convert ids to []int64
	var templateIDs []int64
	for _, idStr := range iDsStr {
		id, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid id value"})
			return
		}
		templateIDs = append(templateIDs, id)
	}

	// Create a slice to hold the text templates
	textTemplates := []models.TextTemplate{}

	// Count the total number of text templates
	var total int64
	countDb := shared.GetDb()
	db := shared.GetDb()
	if len(templateIDs) > 0 {
		countDb = countDb.Where("id IN (?)", templateIDs)
		db = db.Where("id IN (?)", templateIDs)
	}
	if err := countDb.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 := db.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, "data": 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})
}
