package rcuquota

import (
	"math"

	globalcommonv1 "github.com/tidbcloud/tidb-management-service/api/spec/global/common/v1"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/domain/entity"
	"github.com/tidbcloud/tidb-management-service/nextgen-global-service/infra/repoimpl/schema"
)

func entityToSchema(en *entity.RcuQuota) *schema.RcuQuota {
	if en == nil {
		return &schema.RcuQuota{}
	}
	burstAllowancePercentFloat := (en.BurstyRatio * 100.0) - 100.0

	burstAllowancePercent := uint32(math.Round(float64(burstAllowancePercentFloat)))

	return &schema.RcuQuota{
		TenantID:                   en.OrganizationId,
		Quota:                      en.InstanceMaxRcu,
		TotalMaxRCU:                en.TotalMaxRcu,
		BurstAllowancePercent:      &burstAllowancePercent,
		ServicePlan:                en.ServicePlan.String(),
		IdleResourcePoolTtlInHours: uint32(en.IdleResourcePoolTtlInHours),
		VcpusLimitPerResourcePool:  en.VcpusLimitPerResourcePool,
		MinimalRcuBaseline:         en.MinimalRcuBaseline,
		MinimalRcuCoefficient:      en.MinimalRcuCoefficient,
		ScaleDownCooldownMinutes:   en.ScaleDownCooldownMinutes,
	}
}

func schemaToEntity(m *schema.RcuQuota) *entity.RcuQuota {
	if m == nil {
		return &entity.RcuQuota{}
	}
	burstAllowancePercent := uint32(0)
	if m.BurstAllowancePercent != nil {
		burstAllowancePercent = *m.BurstAllowancePercent
	}
	burstyRatio := float32(burstAllowancePercent+100) / 100.0

	return &entity.RcuQuota{
		OrganizationId:             m.TenantID,
		InstanceMaxRcu:             m.Quota,
		TotalMaxRcu:                m.TotalMaxRCU,
		BustyRatio:                 burstyRatio,
		BurstyRatio:                burstyRatio,
		ServicePlan:                globalcommonv1.ServicePlan(globalcommonv1.ServicePlan_value[m.ServicePlan]),
		IdleResourcePoolTtlInHours: uint64(m.IdleResourcePoolTtlInHours),
		VcpusLimitPerResourcePool:  m.VcpusLimitPerResourcePool,
		MinimalRcuBaseline:         m.MinimalRcuBaseline,
		MinimalRcuCoefficient:      m.MinimalRcuCoefficient,
		ScaleDownCooldownMinutes:   m.ScaleDownCooldownMinutes,
	}
}
