package api

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/tidbcloud/billing-verify-bills/pkg/global"
	"github.com/tidbcloud/billing-verify-bills/pkg/verify"
)

type VerifyAPI struct {
	manager *verify.Manager
}

// bill from cloud provider
func (t VerifyAPI) VerifyNetworkBill(c *gin.Context) {
	request := global.Request{}
	err := c.BindJSON(&request)

	if err != nil {
		log.S().Errorf("json error:%s", err)
		c.JSON(http.StatusInternalServerError,
			global.Response{Code: http.StatusInternalServerError, ErrMessage: err.Error()})
		return
	}

	// check time format
	_, err = time.Parse(global.TIME_TEMPLATE, request.StartTime)
	if err != nil {
		c.JSON(http.StatusInternalServerError,
			global.Response{Code: http.StatusInternalServerError, ErrMessage: fmt.Sprintf("keyError:%s,%s", "start_time", err)},
		)
		return
	}
	_, err = time.Parse(global.TIME_TEMPLATE, request.EndTime)
	if err != nil {
		c.JSON(http.StatusInternalServerError,
			global.Response{Code: http.StatusInternalServerError, ErrMessage: fmt.Sprintf("keyError:%s,%s", "end_time", err)},
		)
		return
	}

	ctx := context.Background()

	err = t.manager.VerifyNetworkBill(ctx, request)
	if err != nil {
		c.JSON(http.StatusBadRequest, global.Response{Code: http.StatusInternalServerError, ErrMessage: err.Error()})
		// if the verification failed, we should create an error event to sentry
		// t.Errorf("verification failed, timestamp: ("")
		return
	}

	c.JSON(http.StatusOK, global.Response{Code: http.StatusOK, Data: "ok"})
}

func (t VerifyAPI) Load(g *gin.RouterGroup) {
	g.POST("/billverify/network", t.VerifyNetworkBill)
	// register your verification logic here
	// g.POST("/billverify/billingservice", t.VerifyBillingService)
	// g.POST("/billverify/backup", t.VerifyBackupBill)
	// g.POST("/billverify/cdc", t.VerifyCDCBill)
}

// NewVerifyAPI new api
func NewVerifyAPI(manager *verify.Manager) *VerifyAPI {
	p := &VerifyAPI{manager: manager}
	return p
}
