// Package api provides HTTP handlers for the API Gateway
package api

import (
	"net/http"

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

// =============================================================================
// RAG / Search
// =============================================================================

// SearchRequest represents a RAG search request
type SearchRequest struct {
	Query           string   `json:"query" binding:"required"`
	RegulationCodes []string `json:"regulation_codes,omitempty"`
	Limit           int      `json:"limit,omitempty"`
}

// SearchRAG performs a semantic search
func SearchRAG(c *gin.Context) {
	var req SearchRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// In production, forward to RAG service
	c.JSON(http.StatusOK, gin.H{
		"query": req.Query,
		"results": []gin.H{
			{
				"content":        "Art. 9 Abs. 1 DSGVO verbietet grundsätzlich die Verarbeitung besonderer Kategorien personenbezogener Daten...",
				"regulationCode": "DSGVO",
				"article":        "9",
				"score":          0.95,
			},
		},
		"total": 1,
	})
}

// AskRequest represents a RAG question request
type AskRequest struct {
	Question string `json:"question" binding:"required"`
	Context  string `json:"context,omitempty"`
}

// AskRAG asks a question to the legal assistant
func AskRAG(c *gin.Context) {
	var req AskRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// In production, forward to RAG service
	c.JSON(http.StatusOK, gin.H{
		"question": req.Question,
		"answer":   "Art. 9 DSGVO regelt die Verarbeitung besonderer Kategorien personenbezogener Daten...",
		"citations": []gin.H{
			{
				"regulationCode": "DSGVO",
				"article":        "9",
				"relevance":      0.95,
			},
		},
		"confidence": 0.92,
	})
}

// GetRegulations returns available regulations
func GetRegulations(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"regulations": []gin.H{
			{
				"code":        "DSGVO",
				"name":        "Datenschutz-Grundverordnung",
				"chunks":      99,
				"lastUpdated": "2024-01-01",
			},
			{
				"code":        "AI_ACT",
				"name":        "EU AI Act",
				"chunks":      85,
				"lastUpdated": "2024-01-01",
			},
			{
				"code":        "NIS2",
				"name":        "NIS 2 Directive",
				"chunks":      46,
				"lastUpdated": "2024-01-01",
			},
		},
	})
}

// UploadDocument uploads a custom document for RAG
func UploadDocument(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "No file provided"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"id":       uuid.New().String(),
		"filename": file.Filename,
		"size":     file.Size,
		"status":   "PROCESSING",
		"message":  "Document uploaded and queued for processing",
	})
}
