package api

import (
	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/billing2/billing_errors"
	"github.com/pingcap/dbaas/billing2/forms"
	"github.com/pingcap/dbaas/billing2/model/billing"
	"github.com/pingcap/dbaas/billing2/utils/ginutils"
)

type measureAPI struct {
}

// @Summary Cost Units
// @Schemes
// @Accept json
// @Produce json
// @Param tenant_id path string true "tenant_id"
// @Param Cost body forms.UnitCostsInput true "Cost"
// @Success 200 {object} forms.UnitCosts
// @Router /tenants/{tenant_id}/measures [post]
func (s *measureAPI) CostUnits(c *gin.Context) (ginutils.HandlerFuncResult, error) {
	tenantID, err := getTenantIDFromURI(c)
	if err != nil {
		return nil, err
	}

	costForm := &forms.UnitCosts{}
	if err := c.ShouldBindJSON(costForm); err != nil {
		return nil, billing_errors.NewInvalidInputError(err)
	}

	model := &billing.MeasureModel{}

	info, err := model.CostUnits(tenantID, costForm)
	if err != nil {
		return nil, err
	}
	return info, nil
}

// @Summary Cost Units Dryrun
// @Schemes
// @Accept json
// @Produce json
// @Param tenant_id path string true "tenant_id"
// @Param Cost body forms.UnitCostsInput true "Cost"
// @Success 200 {object} forms.UnitCosts
// @Router /tenants/{tenant_id}/measures/dryrun [post]
func (s *measureAPI) CostUnitsDryrun(c *gin.Context) (ginutils.HandlerFuncResult, error) {
	tenantID, err := getTenantIDFromURI(c)
	if err != nil {
		return nil, err
	}

	costForm := &forms.UnitCosts{}
	if err := c.ShouldBindJSON(costForm); err != nil {
		return nil, billing_errors.NewInvalidInputError(err)
	}

	model := &billing.MeasureModel{}

	info, err := model.CostUnitsDryrun(tenantID, costForm)
	if err != nil {
		return nil, err
	}
	return info, nil
}

func InitializeMeasureRouter(router ginutils.MyRoute) {
	s := &measureAPI{}
	router.HandleWithError("POST", "/tenants/:tenant_id/measures", s.CostUnits)
	router.HandleWithError("POST", "/tenants/:tenant_id/measures/dryrun", s.CostUnitsDryrun)
}
