package producthandler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/kweaver-ai/kweaver-core/decision-agent/agent-backend/agent-factory/src/domain/constant/auditconstant"
	"github.com/kweaver-ai/kweaver-core/decision-agent/agent-backend/agent-factory/src/infra/common/capierr"
	"github.com/kweaver-ai/kweaver-core/decision-agent/agent-backend/agent-factory/src/infra/common/capimiddleware"
	"github.com/kweaver-ai/kweaver-core/decision-agent/agent-backend/agent-factory/src/infra/common/chelper"
	"github.com/kweaver-ai/kweaver-core/decision-agent/agent-backend/agent-factory/src/infra/common/cutil"
	"github.com/kweaver-ai/kweaver-go-lib/audit"
	"github.com/kweaver-ai/kweaver-go-lib/rest"
)

// Delete 删除产品
// @Summary      删除产品
// @Description  根据产品 ID 删除产品
// @Tags         产品
// @Accept       json
// @Produce      json
// @Param        id  path      int  true  "产品 ID"
// @Success      204
// @Failure      400  {object}  swagger.APIError           "请求参数错误"
// @Failure      401  {object}  swagger.APIError           "未授权"
// @Failure      403  {object}  swagger.APIError           "禁止访问"
// @Failure      500  {object}  swagger.APIError           "服务器内部错误"
// @Router       /v3/product/{id} [delete]
// @Security     BearerAuth
func (h *productHTTPHandler) Delete(c *gin.Context) {
	isPrivate := capimiddleware.IsInternalAPI(c)

	var visitor *rest.Visitor

	if !isPrivate {
		visitor = chelper.GetVisitorFromCtx(c.Request.Context())
	}

	id := c.Param("id")
	if id == "" {
		err := capierr.New400Err(c, "id is empty")
		if !isPrivate {
			audit.NewWarnLogWithError(audit.OPERATION, auditconstant.DELETE, audit.TransforOperator(*visitor),
				auditconstant.GenerateProductAuditObject("", ""), &err.BaseError)
		}

		_ = c.Error(err)

		return
	}

	auditloginfo, err := h.productService.Delete(c, cutil.MustParseInt64(id))
	if err != nil {
		httpErr := capierr.New500Err(c, err.Error())
		if !isPrivate {
			audit.NewWarnLogWithError(audit.OPERATION, auditconstant.DELETE, audit.TransforOperator(*visitor),
				auditconstant.GenerateProductAuditObject(auditloginfo.ID, auditloginfo.Name), &httpErr.BaseError)
		}

		_ = c.Error(err)

		return
	}

	if !isPrivate {
		audit.NewWarnLog(audit.OPERATION, auditconstant.DELETE, audit.TransforOperator(*visitor),
			auditconstant.GenerateProductAuditObject(auditloginfo.ID, auditloginfo.Name), audit.SUCCESS, "")
	}

	c.Status(http.StatusNoContent)
}
