package api

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

	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/tidbcloud/cost-collect/pkg/cost"
	"github.com/tidbcloud/cost-collect/pkg/global"
)

type ProviderCostAPI struct {
	manager *cost.Manager
}

// bill from cloud provider
func (t ProviderCostAPI) GetProviderCost(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()

	items, err := t.manager.QueryBill(ctx, request)
	if err != nil {
		c.JSON(http.StatusInternalServerError, global.Response{Code: http.StatusInternalServerError, ErrMessage: err.Error()})
		return
	}

	response := global.Bill{Request: request, Data: items}
	c.JSON(http.StatusOK, global.Response{Code: http.StatusOK, Data: response})

}

func (t ProviderCostAPI) Load(g *gin.RouterGroup) {
	g.POST("/provider/cost", t.GetProviderCost)
}

// NewProviderCostAPI new api
func NewProviderCostAPI(manager *cost.Manager) *ProviderCostAPI {
	p := &ProviderCostAPI{manager: manager}
	return p
}
