package admin

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/mcuadros/go-defaults"
	"net/http"
)

type WafLogHandler struct {
	*handler.Handler
	wafLogService admin.WafLogService
}

func NewWafLogHandler(
    handler *handler.Handler,
    wafLogService admin.WafLogService,
) *WafLogHandler {
	return &WafLogHandler{
		Handler:      handler,
		wafLogService: wafLogService,
	}
}

func (h *WafLogHandler) GetWafLog(ctx *gin.Context) {
	var req adminApi.WafLog
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	defaults.SetDefaults(&req)
	res, err := h.wafLogService.GetWafLog(ctx, int64(req.Id))
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}
	v1.HandleSuccess(ctx, res)
}

func (h *WafLogHandler) GetWafLogList(ctx *gin.Context) {
	var req adminApi.SearchWafLogParams
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	defaults.SetDefaults(&req)
	res, err := h.wafLogService.GetWafLogList(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}
	v1.HandleSuccess(ctx, res)
}

// ExportWafLog 导出WAF日志为Excel文件
func (h *WafLogHandler) ExportWafLog(ctx *gin.Context) {
	var req adminApi.ExportWafLog
	if err := ctx.ShouldBind(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, v1.ErrBadRequest, err.Error())
		return
	}
	defaults.SetDefaults(&req)
	
	// 调用服务层的智能导出方法
	err := h.wafLogService.SmartExportWafLog(ctx, req, ctx.Writer)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, err.Error())
		return
	}
}

// GetApiDescriptions 获取API描述映射
func (h *WafLogHandler) GetApiDescriptions(ctx *gin.Context) {
	res := h.wafLogService.GetApiDescriptions(ctx)
	v1.HandleSuccess(ctx, res)
}