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 {
		_, err := c.service.CreateWaf(ctx1, &r)
		if err != nil {
			utils.AssembleResponse(ctx, nil, err)
			return
		}
	}
	utils.AssembleResponse(ctx, nil, nil)
}

// `
// curl -X POST http://127.0.0.1:8080/v1/api/waf \
//      -H "Content-Type: application/json" \
//      -d '[
//            {
//              "region_code": "cn-east-1",
//              "gatewayname": "istio-ingressgateway",
// 			 "namespace": "istio-system",
// 			 "port": 80,
// 			 "host": ["*"]
//            }
//          ]'
// `
