package handlers

import (
	"net/http"

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

// ============================================================================
// Matrix Endpoints
// ============================================================================

// GetMatrix returns the full CTM for the tenant
// GET /sdk/v1/training/matrix
func (h *TrainingHandlers) GetMatrix(c *gin.Context) {
	tenantID := rbac.GetTenantID(c)

	entries, err := h.store.GetMatrixForTenant(c.Request.Context(), tenantID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	resp := training.BuildMatrixResponse(entries)
	c.JSON(http.StatusOK, resp)
}

// GetMatrixForRole returns matrix entries for a specific role
// GET /sdk/v1/training/matrix/:role
func (h *TrainingHandlers) GetMatrixForRole(c *gin.Context) {
	tenantID := rbac.GetTenantID(c)
	role := c.Param("role")

	entries, err := h.store.GetMatrixForRole(c.Request.Context(), tenantID, role)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"role":    role,
		"label":   training.RoleLabels[role],
		"entries": entries,
		"total":   len(entries),
	})
}

// SetMatrixEntry creates or updates a CTM entry
// POST /sdk/v1/training/matrix
func (h *TrainingHandlers) SetMatrixEntry(c *gin.Context) {
	tenantID := rbac.GetTenantID(c)

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

	entry := &training.TrainingMatrixEntry{
		TenantID:    tenantID,
		RoleCode:    req.RoleCode,
		ModuleID:    req.ModuleID,
		IsMandatory: req.IsMandatory,
		Priority:    req.Priority,
	}

	if err := h.store.SetMatrixEntry(c.Request.Context(), entry); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, entry)
}

// DeleteMatrixEntry removes a CTM entry
// DELETE /sdk/v1/training/matrix/:role/:moduleId
func (h *TrainingHandlers) DeleteMatrixEntry(c *gin.Context) {
	tenantID := rbac.GetTenantID(c)
	role := c.Param("role")
	moduleID, err := uuid.Parse(c.Param("moduleId"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid module ID"})
		return
	}

	if err := h.store.DeleteMatrixEntry(c.Request.Context(), tenantID, role, moduleID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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