package log

import (
	"errors"
	"log"
	"strings"

	"bsm/full/module/base/logs/internal/impl"
	"bsm/full/module/base/logs/internal/models"
	"git.apinb.com/bsm-sdk/core/infra"
	"github.com/gin-gonic/gin"
)

func Create(c *gin.Context) {
	var (
		request = make([]*models.LogData, 0)
	)

	// 验证请求IP，禁止公网网段提交
	ip := c.ClientIP()
	if ip == "127.0.0.1" || ip == "localhost" || strings.HasPrefix(ip, "10.") || strings.HasPrefix(ip, "172.") || strings.HasPrefix(ip, "192.") {
		log.Printf("request ip is not allowed")
		err := errors.New("request ip is not allowed")
		infra.Response.Error(c, err)
		return
	}

	err := c.BindJSON(&request)
	if err != nil {
		log.Printf("parse json error: %v", err)
		infra.Response.Error(c, err)
		return
	}
	if len(request) == 0 {
		log.Printf("request data is empty")
		infra.Response.Error(c, errors.New("request data is empty"))
		return
	}

	if err := impl.DBService.Model(&models.LogData{}).Create(&request).Error; err != nil {
		log.Printf("save log data error: %v", err)
		infra.Response.Error(c, err)
		return
	}

	infra.Response.Success(c, "")
}
