package controllers

import (
	"ems-backend/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

// GetCleaningTemplates lists all cleaning templates
func GetCleaningTemplates(c *gin.Context) {
	var templates []models.EquipmentCleaningFormulaTemplate
	if err := models.DB.Order("created_at desc").Find(&templates).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": templates})
}

// CreateCleaningTemplate creates a new cleaning template
func CreateCleaningTemplate(c *gin.Context) {
	var template models.EquipmentCleaningFormulaTemplate
	if err := c.ShouldBindJSON(&template); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := models.DB.Create(&template).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": template})
}

// UpdateCleaningTemplate updates an existing cleaning template
func UpdateCleaningTemplate(c *gin.Context) {
	id := c.Param("id")
	var template models.EquipmentCleaningFormulaTemplate
	if err := models.DB.First(&template, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Template not found"})
		return
	}

	if err := c.ShouldBindJSON(&template); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := models.DB.Save(&template).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": template})
}

// DeleteCleaningTemplate deletes a cleaning template
func DeleteCleaningTemplate(c *gin.Context) {
	id := c.Param("id")
	if err := models.DB.Delete(&models.EquipmentCleaningFormulaTemplate{}, "id = ?", id).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Template deleted"})
}

