package handlers

import (
	"net/http"
	"strconv"

	"github.com/breakpilot/ai-compliance-sdk/internal/ucca"
	"github.com/gin-gonic/gin"
)

// RegulatoryNewsHandlers serves regulatory news from obligation v2 data.
type RegulatoryNewsHandlers struct {
	regulations map[string]*ucca.V2RegulationFile
}

// NewRegulatoryNewsHandlers creates a handler backed by pre-loaded regulation data.
func NewRegulatoryNewsHandlers(regs map[string]*ucca.V2RegulationFile) *RegulatoryNewsHandlers {
	return &RegulatoryNewsHandlers{regulations: regs}
}

// GetNews returns upcoming regulatory deadlines sorted by urgency.
func (h *RegulatoryNewsHandlers) GetNews(c *gin.Context) {
	filter := ucca.RegulatoryNewsFilter{
		BusinessModel: c.Query("business_model"),
		HorizonDays:   parseIntOrDefault(c.Query("horizon_days"), 365),
		Limit:         parseIntOrDefault(c.Query("limit"), 5),
	}

	items := ucca.GetRegulatoryNews(h.regulations, filter)
	c.JSON(http.StatusOK, gin.H{"items": items, "total": len(items)})
}

func parseIntOrDefault(s string, def int) int {
	if s == "" {
		return def
	}
	v, err := strconv.Atoi(s)
	if err != nil {
		return def
	}
	return v
}
