package automation

import (
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/api/meshxapi"
	automationservice "github.com/tidbcloud/AgentTeam/internal/service/automation"
)

func automationErrorHandling() meshxapi.HandlerOption {
	return meshxapi.WithErrorClassifier(func(err error) (meshxapi.ErrorResponse, bool) {
		status := automationservice.AutomationHTTPStatus(err)
		if status == http.StatusInternalServerError {
			return meshxapi.ErrorResponse{}, false
		}
		return meshxapi.ErrorResponse{Status: status, Message: err.Error(), Code: automationservice.AutomationCode(err), Details: automationservice.AutomationDetails(err)}, true
	})
}

func writeAutomationHandlerError(w http.ResponseWriter, err error) {
	status := automationservice.AutomationHTTPStatus(err)
	if status != http.StatusInternalServerError {
		code := strings.TrimSpace(automationservice.AutomationCode(err))
		if code == "" {
			code = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(err.Error()), " ", "_"))
		}
		body := map[string]any{
			"error":   code,
			"message": err.Error(),
		}
		if details := automationservice.AutomationDetails(err); details != nil {
			body["details"] = details
		}
		meshxapi.WriteResponse(w, meshxapi.Response{
			Status: status,
			Body:   body,
		})
		return
	}
	meshxapi.WriteError(w, err)
}
