package configeval

import (
	"context"
	"fmt"

	"sigs.k8s.io/controller-runtime/pkg/client"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
)

// Ideally those values should be retrieved from the InfraAPI server
// However they are hardcoded here due to the module dependencies
// They would be moved into a single source with the clusterconfig controller v2
const (
	PDGp3IOPS           = "4000"
	PDGp3ThroughputMBps = "400"

	TiKVGp3IOPS           = "4000"
	TiKVGp3ThroughputMBps = "400"

	TiFlashGp3IOPS           = "6000"
	TiFlashGp3ThroughputMBps = "625"

	TiCDCGp3IOPS           = "4000"
	TiCDCGp3ThroughputMBps = "400"
)

func FindInstanceType(infraApiCli client.Client, providerType, machineType string) (*cloudv1.InstanceType, error) {
	providerList := new(cloudv1.ProviderList)
	err := infraApiCli.List(context.TODO(), providerList)
	if err != nil {
		return nil, err
	}

	provider := new(cloudv1.Provider)

	for i := range providerList.Items {
		if providerList.Items[i].Spec.Type == providerType {
			provider = &providerList.Items[i]
			break
		}
	}

	for _, t := range provider.Spec.InstanceTypes {
		if t.Name == machineType {
			return &t, nil
		}
	}
	return nil, fmt.Errorf("cannot find instance type: %s from provider: %s", machineType, providerType)
}

func FindMachineType(c *cloudv1.Cluster, compName cloudv1.ComponentType) string {
	if c == nil {
		return ""
	}
	switch compName {
	case "pd":
		return c.Spec.Cluster.PD.InstanceType
	case "tidb":
		return c.Spec.Cluster.TiDB.InstanceType
	case "tikv":
		return c.Spec.Cluster.TiKV.InstanceType
	case "tiflash":
		return c.Spec.Cluster.TiFlash.InstanceType
	default:
		return ""
	}
}
