package handlers

import (
	"errors"
	"net/http"

	"github.com/acp/interceptor/internal/models"
	"github.com/acp/interceptor/internal/services"
	"github.com/acp/interceptor/internal/tracing"
	"github.com/acp/interceptor/internal/utils"
	"github.com/gin-gonic/gin"
)

// ToolHandler serves POST /tool-call.
type ToolHandler struct {
	svc *services.InterceptorService
}

// NewToolHandler constructs a tool handler.
func NewToolHandler(svc *services.InterceptorService) *ToolHandler {
	return &ToolHandler{svc: svc}
}

// HandleToolCall binds JSON, runs interception, returns decision.
func (h *ToolHandler) HandleToolCall(c *gin.Context) {
	traceID := tracing.TraceIDFromContext(c)
	var req models.ToolCallRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.AbortWithValidation(c, traceID, err)
		return
	}

	ctx := c.Request.Context()
	resp, err := h.svc.HandleToolCall(ctx, services.CallContext{
		TraceID:    traceID,
		HTTPPath:   c.FullPath(),
		HTTPMethod: c.Request.Method,
	}, req)
	if err != nil {
		var v utils.ValidationError
		if errors.As(err, &v) {
			utils.AbortWithValidation(c, traceID, err)
			return
		}
		utils.AbortWithErrorJSON(c, http.StatusBadGateway, traceID, "policy evaluation failed")
		return
	}

	c.Header(tracing.TraceIDHeader, traceID)
	utils.JSON(c, http.StatusOK, resp)
}
