package collectors

import (
	"context"

	"github.com/go-logr/logr"
	"github.com/prometheus/client_golang/prometheus"
	v1 "github.com/tidbcloud/ticdc-service-ng/api/v1"
	"github.com/tidbcloud/ticdc-service-ng/pkg/consts"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

var (
	ticdcInfo = prometheus.NewDesc(
		"ticdc_service_ticdc_info",
		"Information about ticdc CR.",
		[]string{
			"name",
			"cluster_id",
			"region",
			"status",
		}, nil)
)

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

var _ prometheus.Collector = &ticdc{}

func (b *ticdc) Describe(ch chan<- *prometheus.Desc) {
	ch <- ticdcInfo
}

func (b *ticdc) Collect(ch chan<- prometheus.Metric) {
	ticdcList := &v1.TiCDCList{}
	if err := b.cli.List(context.Background(), ticdcList); err != nil {
		b.log.Error(err, "fetching bucketList")
		return
	}
	for _, ticdcCR := range ticdcList.Items {
		sharedPool := ticdcCR.Spec.SharedPoolID
		region := ticdcCR.GetLabels()[consts.RegionLabel]

		ch <- prometheus.MustNewConstMetric(
			ticdcInfo,
			prometheus.GaugeValue,
			1,
			ticdcCR.Name,
			sharedPool,
			region,
			string(ticdcCR.Status.Phase),
		)
	}
}
