package handlers

import (
	"fmt"
	"net/http"

	"git.linuxforward.com/byop/byop-engine/models"
	"git.linuxforward.com/byop/byop-engine/services"
	"github.com/gin-gonic/gin"
)

// TemplateHandler handles template-related operations
type TemplateHandler struct {
	service *services.TemplateService
}

// NewTemplateHandler creates a new TemplateHandler
func NewTemplateHandler(service *services.TemplateService) *TemplateHandler {
	return &TemplateHandler{
		service: service,
	}
}

// ListTemplates returns all templates with optional filtering
func (h *TemplateHandler) ListTemplates(c *gin.Context) {
	filter := make(map[string]interface{})

	// Attempt to bind query parameters, but allow empty filters
	if err := c.ShouldBindQuery(&filter); err != nil && len(filter) > 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid query parameters"})
		return
	}

	templates, err := h.service.ListTemplates(filter)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to list templates: %v", err)})
		return
	}

	c.JSON(http.StatusOK, templates)
}

// CreateTemplate creates a new deployment template
func (h *TemplateHandler) CreateTemplate(c *gin.Context) {
	var template models.Template

	if err := c.ShouldBindJSON(&template); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Invalid request body: %v", err)})
		return
	}

	// Get the user ID from the context (set by auth middleware)
	userID, exists := c.Get("userID")
	if exists {
		template.CreatedBy = userID.(string)
	}

	if err := h.service.CreateTemplate(&template); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to create template: %v", err)})
		return
	}

	c.JSON(http.StatusCreated, template)
}

// GetTemplate returns a specific template
func (h *TemplateHandler) GetTemplate(c *gin.Context) {
	id := c.Param("id")

	template, err := h.service.GetTemplate(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to fetch template: %v", err)})
		return
	}

	if template == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Template not found"})
		return
	}

	c.JSON(http.StatusOK, template)
}

// UpdateTemplate updates a template
func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {
	id := c.Param("id")

	var updatedTemplate models.Template
	if err := c.ShouldBindJSON(&updatedTemplate); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Invalid request body: %v", err)})
		return
	}

	// Ensure the ID matches the URL parameter
	updatedTemplate.ID = id

	if err := h.service.UpdateTemplate(&updatedTemplate); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to update template: %v", err)})
		return
	}

	c.JSON(http.StatusOK, updatedTemplate)
}

// DeleteTemplate deletes a template
func (h *TemplateHandler) DeleteTemplate(c *gin.Context) {
	id := c.Param("id")

	if err := h.service.DeleteTemplate(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to delete template: %v", err)})
		return
	}

	c.Status(http.StatusNoContent)
}

// GetTemplateDeployments returns all deployments for a template
func (h *TemplateHandler) GetTemplateDeployments(c *gin.Context) {
	id := c.Param("id")

	deployments, err := h.service.GetTemplateDeployments(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to fetch template deployments: %v", err)})
		return
	}

	c.JSON(http.StatusOK, deployments)
}

// GetTemplateByVersion handles retrieval of a template by name and version
func (h *TemplateHandler) GetTemplateByVersion(c *gin.Context) {
	name := c.Query("name")
	version := c.Query("version")

	if name == "" || version == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Both name and version parameters are required"})
		return
	}

	template, err := h.service.GetTemplateByVersion(name, version)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Failed to fetch template: %v", err)})
		return
	}

	if template == nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Template not found"})
		return
	}

	c.JSON(http.StatusOK, template)
}
