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"
)

// BlueprintHandler handles blueprint-related operations
type BlueprintHandler struct {
	service *services.BlueprintService
}

// NewBlueprintHandler creates a new BlueprintHandler
func NewBlueprintHandler(service *services.BlueprintService) *BlueprintHandler {
	return &BlueprintHandler{
		service: service,
	}
}

// ListBlueprints returns all blueprints with optional filtering
func (h *BlueprintHandler) ListBlueprints(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
	}

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

	c.JSON(http.StatusOK, blueprints)
}

// CreateBlueprint creates a new deployment blueprint
func (h *BlueprintHandler) CreateBlueprint(c *gin.Context) {
	var blueprint models.Blueprint

	if err := c.ShouldBindJSON(&blueprint); 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 {
		blueprint.CreatedBy = userID.(string)
	}

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

	c.JSON(http.StatusCreated, blueprint)
}

// GetBlueprint returns a specific blueprint
func (h *BlueprintHandler) GetBlueprint(c *gin.Context) {
	id := c.Param("id")

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

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

	c.JSON(http.StatusOK, blueprint)
}

// UpdateBlueprint updates a blueprint
func (h *BlueprintHandler) UpdateBlueprint(c *gin.Context) {
	id := c.Param("id")

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

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

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

	c.JSON(http.StatusOK, updatedBlueprint)
}

// DeleteBlueprint deletes a blueprint
func (h *BlueprintHandler) DeleteBlueprint(c *gin.Context) {
	id := c.Param("id")

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

	c.Status(http.StatusNoContent)
}

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

	deployments, err := h.service.GetBlueprintDeployments(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)
}

// GetBlueprintByVersion handles retrieval of a template by name and version
func (h *BlueprintHandler) GetBlueprintByVersion(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.GetBlueprintByVersion(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": "Blueprint not found"})
		return
	}

	c.JSON(http.StatusOK, template)
}
