package datasource

import (
	"github.com/pingcap/dbaas/central/db"
	"github.com/pingcap/dbaas/central/db/dbutil"
	"github.com/pingcap/dbaas/central/db/entity"
	"github.com/pingcap/errors"
	"gorm.io/gorm"
)

var (
	// Docs: https://jira.tidbcloud.com/browse/DM-1247.
	// For now, only Colopl, Colopl.Inc, Toppan, and PingCAP(for debug) show it.
	tenantIDPermitToScrapeNodeMemory = map[uint64]bool{
		entity.PingCAPTenantID.Uint64(): true, // for debug
		1326455380288475136:             true, // Colopl
		1372813089187641281:             true, // Colopl.Inc
		1372813089187971283:             true, // Toppan
	}
)

func IsOKToScrapeNodeMemory(clusterID uint64) error {
	var (
		cluster entity.Cluster
		err     error
	)
	err = db.Transaction(func(tx *gorm.DB) error {
		cluster, err = dbutil.GetCluster(tx, entity.ID(clusterID))
		return err
	})
	if err != nil {
		return errors.Annotate(err, "cluster not found")
	}
	if allowed, ok := tenantIDPermitToScrapeNodeMemory[cluster.TenantID.Uint64()]; !ok || !allowed {
		return errors.Errorf("the current cluster is not allowed to show the node memory used metrics: tenant_id %d, cluster_id %d, cluster_name %s", cluster.TenantID.Uint64(), cluster.ID.Uint64(), cluster.Name)
	}
	return nil
}
