package controller

import (
	"context"
	"time"

	"github.com/gin-gonic/gin"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/service"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/utils"
	"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
	"gorm.io/gorm"
)

type WafController struct {
	service service.Service
}

func NewWafController(client *versioned.Clientset, db *gorm.DB) *WafController {
	return &WafController{
		service: service.NewWafService(client, db),
	}
}

func (c *WafController) Waf(ctx *gin.Context) {
	ctx1, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	gatewayName := ctx.Param("gateway_name")
	waf, err := c.service.GetWaf(ctx1, gatewayName)
	if err != nil {
		// logging.Get().Err(err).Msgf("get waf")
		utils.AssembleResponse(ctx, nil, err)
		return
	}
	resp := &utils.SingleRespData{
		Item: waf,
	}
	utils.AssembleResponse(ctx, resp, nil)
}

func (c *WafController) CreateWaf(ctx *gin.Context) {
	ctx1, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	var req []service.CreateWafReq
	if err := ctx.BindJSON(&req); err != nil {
		utils.AssembleResponse(ctx, nil, err)
		return
	}
	for _, r := range req {
		c.service.CreateWaf(ctx1, &r)
	}
	utils.AssembleResponse(ctx, nil, nil)
}
