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/costexplorer"
	"github.com/pingcap/dbaas/billing2/utils/ginutils"
)

type usageExplorerAPI struct {
}

// @Summary DataAPI usage Explorer Monthly
// @Schemes
// @Accept json
// @Produce json
// @Param tenant_id path string true "tenant_id"
// @Param year path string true "year"
// @Param month path string true "month"
// @Param app_id path string true "app_id"
// @Success 200 {object} forms.DataAPIUsageExplore
// @Router /tenants/{tenant_id}/costexplorer/monthly_usage/dataapi/apps/{app_id}/year/{year}/month/{month} [get]
func (s *usageExplorerAPI) DataAPIMonthlyUsage(c *gin.Context) (ginutils.HandlerFuncResult, error) {
	param := &forms.MonthlyUsageURI{}
	if err := c.ShouldBindUri(param); err != nil {
		return nil, billing_errors.NewInvalidInputError(err)
	}
	model := &costexplorer.UsageExplorerModel{}

	query, err := model.GetMonthlyAppUsageWithCache(*param)
	if err != nil {
		return nil, billing_errors.NewSystemError(err)
	}
	query.Month = param.Month
	return query.DataAPIUsageExplore, nil
}

// @Summary app usage Explorer Monthly
// @Schemes
// @Accept json
// @Produce json
// @Param tenant_id path string true "tenant_id"
// @Param year path string true "year"
// @Param month path string true "month"
// @Param app_name path string true "app_name"
// @Param app_id path string true "app_id"
// @Success 200 {object} forms.AppAPIUsageExplore
// @Router /tenants/{tenant_id}/costexplorer/monthly_usage/app/{app_name}/apps/{app_id}/year/{year}/month/{month} [get]
func (s *usageExplorerAPI) AppUsageMonthlyUsage(c *gin.Context) (ginutils.HandlerFuncResult, error) {
	param := &forms.MonthlyUsageURI{}
	if err := c.ShouldBindUri(param); err != nil {
		return nil, billing_errors.NewInvalidInputError(err)
	}
	model := &costexplorer.UsageExplorerModel{}

	query, err := model.GetMonthlyAppUsageWithCache(*param)
	if err != nil {
		return nil, billing_errors.NewSystemError(err)
	}
	query.Month = param.Month
	return query, nil
}

func InitializeUsageExplorerRouter(router ginutils.MyRoute) {
	s := &usageExplorerAPI{}
	router.HandleWithError("GET", "/tenants/:tenant_id/costexplorer/monthly_usage/dataapi/apps/:app_id/year/:year/month/:month", s.DataAPIMonthlyUsage)
	router.HandleWithError("GET", "/tenants/:tenant_id/costexplorer/monthly_usage/app/:app_name/apps/:app_id/year/:year/month/:month", s.AppUsageMonthlyUsage)

}
