package handlers

import (
	"net/http"

	"github.com/breakpilot/ai-compliance-sdk/internal/iace"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// ListCustomerStandardSuggestions handles
//   GET /api/v1/iace/projects/:id/customer-standards?include_verified=true|false
//
// Returns the set of reusable mitigations from prior projects of the same
// customer. Empty array when the project has no customer_name or no
// matching priors. The include_verified query flag controls whether
// status='verified' mitigations are included alongside the explicit
// is_customer_standard=true ones.
func (h *IACEHandler) ListCustomerStandardSuggestions(c *gin.Context) {
	pid, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project ID"})
		return
	}
	includeVerified := c.Query("include_verified") == "true"
	suggestions, err := h.store.ListCustomerStandardSuggestions(c.Request.Context(), pid, includeVerified)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if suggestions == nil {
		suggestions = []iace.CustomerStandardSuggestion{}
	}
	c.JSON(http.StatusOK, gin.H{
		"suggestions": suggestions,
		"count":       len(suggestions),
	})
}

// ImportCustomerStandardSuggestion handles
//   POST /api/v1/iace/projects/:id/customer-standards/import
//   Body: { "name": "Sicherheitszeichen nach ISO 7010" }
//
// Applies one suggestion to all matching hazards in the current project.
// New mitigations are created idempotently; existing ones are flipped to
// is_relevant=true + is_customer_standard=true + status='verified'.
func (h *IACEHandler) ImportCustomerStandardSuggestion(c *gin.Context) {
	pid, err := uuid.Parse(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project ID"})
		return
	}
	var body struct {
		Name string `json:"name" binding:"required"`
	}
	if err := c.ShouldBindJSON(&body); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	n, err := h.store.ImportCustomerStandardSuggestion(c.Request.Context(), pid, body.Name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"imported": n,
		"name":     body.Name,
	})
}
