package collectors

import (
	"context"

	"github.com/go-logr/logr"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/consts"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

var (
	bucketInfo = prometheus.NewDesc(
		"dataplane_manager_bucket_info",
		"Information about bucket CR.",
		[]string{
			"name",
			"dataplane",
			"tenant_id",
			"region",
			"status",
		}, nil)
)

type bucket struct {
	cli client.Client
	log logr.Logger
}

var _ prometheus.Collector = &bucket{}

func (b *bucket) Describe(ch chan<- *prometheus.Desc) {
	ch <- bucketInfo
}

func (b *bucket) Collect(ch chan<- prometheus.Metric) {
	bucketList := &v1alpha1.BucketList{}
	if err := b.cli.List(context.Background(), bucketList); err != nil {
		b.log.Error(err, "fetching bucketList")
		return
	}
	for _, bucketCR := range bucketList.Items {
		tenant := bucketCR.GetLabels()[consts.TenantLabelKey]
		dataplane := bucketCR.Spec.DataplaneId

		ch <- prometheus.MustNewConstMetric(
			bucketInfo,
			prometheus.GaugeValue,
			1,
			bucketCR.Name,
			dataplane,
			tenant,
			bucketCR.Spec.Region,
			string(bucketCR.Status.Phase),
		)
	}
}
