package handlers

import (
	"context"
	"net/http"

	"github.com/breakpilot/consent-service/internal/models"
	"github.com/gin-gonic/gin"
)

// ========================================
// PUBLIC ENDPOINTS - Documents
// ========================================

// GetDocuments returns all active legal documents
func (h *Handler) GetDocuments(c *gin.Context) {
	ctx := context.Background()

	rows, err := h.db.Pool.Query(ctx, `
		SELECT id, type, name, description, is_mandatory, is_active, sort_order, created_at, updated_at
		FROM legal_documents
		WHERE is_active = true
		ORDER BY sort_order ASC
	`)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch documents"})
		return
	}
	defer rows.Close()

	var documents []models.LegalDocument
	for rows.Next() {
		var doc models.LegalDocument
		if err := rows.Scan(&doc.ID, &doc.Type, &doc.Name, &doc.Description,
			&doc.IsMandatory, &doc.IsActive, &doc.SortOrder, &doc.CreatedAt, &doc.UpdatedAt); err != nil {
			continue
		}
		documents = append(documents, doc)
	}

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

// GetDocumentByType returns a document by its type
func (h *Handler) GetDocumentByType(c *gin.Context) {
	docType := c.Param("type")
	ctx := context.Background()

	var doc models.LegalDocument
	err := h.db.Pool.QueryRow(ctx, `
		SELECT id, type, name, description, is_mandatory, is_active, sort_order, created_at, updated_at
		FROM legal_documents
		WHERE type = $1 AND is_active = true
	`, docType).Scan(&doc.ID, &doc.Type, &doc.Name, &doc.Description,
		&doc.IsMandatory, &doc.IsActive, &doc.SortOrder, &doc.CreatedAt, &doc.UpdatedAt)

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

	c.JSON(http.StatusOK, doc)
}

// GetLatestDocumentVersion returns the latest published version of a document
func (h *Handler) GetLatestDocumentVersion(c *gin.Context) {
	docType := c.Param("type")
	language := c.DefaultQuery("language", "de")
	ctx := context.Background()

	var version models.DocumentVersion
	err := h.db.Pool.QueryRow(ctx, `
		SELECT dv.id, dv.document_id, dv.version, dv.language, dv.title, dv.content,
		       dv.summary, dv.status, dv.published_at, dv.created_at, dv.updated_at
		FROM document_versions dv
		JOIN legal_documents ld ON dv.document_id = ld.id
		WHERE ld.type = $1 AND dv.language = $2 AND dv.status = 'published'
		ORDER BY dv.published_at DESC
		LIMIT 1
	`, docType, language).Scan(&version.ID, &version.DocumentID, &version.Version, &version.Language,
		&version.Title, &version.Content, &version.Summary, &version.Status,
		&version.PublishedAt, &version.CreatedAt, &version.UpdatedAt)

	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "No published version found"})
		return
	}

	c.JSON(http.StatusOK, version)
}
