package collectors

import (
	"context"
	"strconv"

	"github.com/go-logr/logr"
	"github.com/prometheus/client_golang/prometheus"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/tidbcloud/infra-provider/regional-server/api/v1alpha1"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/common/utils"
	"github.com/tidbcloud/infra-provider/regional-server/pkg/consts"
)

var (
	appBoxInfo = prometheus.NewDesc(
		"dataplane_manager_appbox_info",
		"Information about appBox CR.",
		[]string{
			"name",
			"dataplane",
			"tenant_id",
			"region",
			"provider",
			"vpc",
			"service_type",
			"status",
			"paused",
		}, nil)
)

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

var _ prometheus.Collector = &appBox{}

func (a *appBox) Describe(ch chan<- *prometheus.Desc) {
	ch <- appBoxInfo
}

func (a *appBox) Collect(ch chan<- prometheus.Metric) {
	appBoxList := &v1alpha1.APPBoxList{}
	if err := a.cli.List(context.Background(), appBoxList); err != nil {
		a.log.Error(err, "fetching appboxList")
		return
	}
	for _, appBoxCR := range appBoxList.Items {
		var vpc string
		if appBoxCR.Spec.VPCRef != nil {
			vpc = appBoxCR.Spec.VPCRef.Name
		}
		paused := utils.IsPaused(&appBoxCR)

		tenant := appBoxCR.GetLabels()[consts.TenantLabelKey]
		serviceType := appBoxCR.GetLabels()[consts.ServiceTypeLabelKey]

		ch <- prometheus.MustNewConstMetric(
			appBoxInfo,
			prometheus.GaugeValue,
			1.0,
			appBoxCR.Name,
			appBoxCR.Status.KubernetesClusterName,
			tenant,
			appBoxCR.Spec.Region,
			appBoxCR.Spec.Provider,
			vpc,
			serviceType,
			string(appBoxCR.Status.Phase),
			strconv.FormatBool(paused),
		)
	}
}
