package waf

import (
	"github.com/gin-gonic/gin"
	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
	adminApi "github.com/go-nunu/nunu-layout-advanced/api/v1/admin"
	"github.com/go-nunu/nunu-layout-advanced/internal/handler"
	"github.com/go-nunu/nunu-layout-advanced/internal/service/admin"
	"github.com/go-nunu/nunu-layout-advanced/internal/service/api/waf"
	"net/http"
)

type CcHandler struct {
	*handler.Handler
	ccService waf.CcService
	wafLogService admin.WafLogService
}

func NewCcHandler(
    handler *handler.Handler,
    ccService waf.CcService,
	wafLogService admin.WafLogService,
) *CcHandler {
	return &CcHandler{
		Handler:      handler,
		ccService: ccService,
		wafLogService : wafLogService,
	}
}

func (h *CcHandler) GetCcList(ctx *gin.Context) {
	var req v1.CCListRequest
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	resp, err := h.ccService.GetCcList(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}
	v1.HandleSuccess(ctx, resp)
}

func (h *CcHandler) EditCcState(ctx *gin.Context) {
	var req v1.CCStateRequest
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	err := h.ccService.EditCcState(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}

	go  h.wafLogService.PublishIpWafLogTask(ctx,adminApi.WafLog{
		Uid:       int(req.Uid),
		RequestIp: ctx.ClientIP(), // 复制 ClientIP
		UserAgent: ctx.Request.UserAgent(), // 复制 UserAgent
		Api:       ctx.Request.URL.Path, // 复制 Path
		HostId: int(req.HostId),
		ExtraData: req,
	})
	v1.HandleSuccess(ctx, nil)
}

func (h *CcHandler) AddWhiteOneClick (ctx *gin.Context) {
	var req v1.CCStateRequest
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	err := h.ccService.AddWhiteOneClick(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}

	go  h.wafLogService.PublishIpWafLogTask(ctx,adminApi.WafLog{
		Uid:       int(req.Uid),
		RequestIp: ctx.ClientIP(), // 复制 ClientIP
		UserAgent: ctx.Request.UserAgent(), // 复制 UserAgent
		Api:       ctx.Request.URL.Path, // 复制 Path
		HostId: int(req.HostId),
		ExtraData: req,
	})
	v1.HandleSuccess(ctx, nil)
}
