package handlers

import (
	"net/http"

	"github.com/acp/interceptor/internal/policycatalog"
	"github.com/gin-gonic/gin"
)

// PolicyCatalogHandler serves Rego file metadata scanned from disk (POLICIES_DIR).
type PolicyCatalogHandler struct {
	PoliciesDir string
}

// NewPolicyCatalogHandler constructs a catalog handler.
func NewPolicyCatalogHandler(policiesDir string) *PolicyCatalogHandler {
	return &PolicyCatalogHandler{PoliciesDir: policiesDir}
}

// ListCatalog returns JSON describing .rego modules under POLICIES_DIR.
func (h *PolicyCatalogHandler) ListCatalog(c *gin.Context) {
	if h == nil || h.PoliciesDir == "" {
		c.JSON(http.StatusOK, gin.H{
			"policies": []any{},
			"warning":  "POLICIES_DIR is not set; mount policies and set POLICIES_DIR on the interceptor (see README).",
		})
		return
	}
	entries, err := policycatalog.Scan(h.PoliciesDir)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"policies": entries})
}
