package api

import (
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/billing2/forms"
	"github.com/pingcap/dbaas/billing2/model/marketing/discount"
	"github.com/pingcap/dbaas/billing2/utils/ginutils"
	"github.com/shopspring/decimal"
)

// @Tags MSP
// @Summary Return discounts applied to a specific MSP
// @Description  This endpoint retrieves the discount applied to a specific MSP.
// @Schemes
// @Accept json
// @Produce json
// @Success 200 {object} []forms.MspDiscount
// @Failure 400  {object}  billing_errors.BaseError
// @Router /discounts/ [GET]
func (s *API) ListMspDiscounts(c *gin.Context) (ret ginutils.HandlerFuncResult, retErr error) {
	billingCfgStruct, err := getBillingCfgFromURI(c)
	if err != nil {
		return nil, err
	}
	discounts, err := (&discount.Model{}).ListDiscountsConsoleView(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)
	if err != nil {
		return nil, err
	}
	var mspDiscounts = []forms.MspDiscount{}

	for _, discount := range discounts {
		var names []string
		for _, filter := range discount.UnitFilters {
			names = append(names, filter.Name)
		}
		mspDiscounts = append(mspDiscounts, forms.MspDiscount{
			DiscountCode:       discount.Code,
			Status:             discount.Status,
			Services:           strings.Join(names, ", "),
			PercentageDiscount: decimal.NewFromFloat(1.00).Sub(discount.Value).Mul(decimal.NewFromInt(100)).String() + "%",
			Description:        discount.Description,
			StartDate:          discount.StartedAt,
			ExpiryDate:         discount.ExpiredAt,
		})
	}

	return mspDiscounts, nil
}
func InitializeMspOpenAPIDiscountsRouter(router ginutils.MyRoute) {
	s := &API{}
	router.HandleWithError("GET", "/tenants/:tenant_id/discounts", s.ListMspDiscounts)
	router.HandleWithError("GET", "/discounts", s.ListMspDiscounts)
}
