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/common/utils"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

var (
	appRouteInfo = prometheus.NewDesc(
		"regional_server_approute_info",
		"Information about appRoute CR.",
		[]string{
			"name",
			"tenant_id",
			"project_id",
			"vpc",
			"appbox",
			"status",
		}, nil)
)

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

var _ prometheus.Collector = &appRoute{}

func (a *appRoute) Describe(ch chan<- *prometheus.Desc) {
	ch <- appRouteInfo
}

func (a *appRoute) Collect(ch chan<- prometheus.Metric) {
	appRouteList := &v1alpha1.APPRouteList{}
	if err := a.cli.List(context.Background(), appRouteList); err != nil {
		a.log.Error(err, "fetching approutes")
		return
	}
	for _, appRouteCR := range appRouteList.Items {
		var vpc, appbox string
		if appRouteCR.Spec.VPCRef != nil {
			vpc = appRouteCR.Spec.VPCRef.Name
		}
		if appRouteCR.Spec.APPBoxRef != nil {
			appbox = appRouteCR.Spec.APPBoxRef.Name
		}

		var tenant, project string
		tenants, projects := utils.GetRelatedTenantProjects(appRouteCR.GetLabels())
		if len(tenants) == 1 && len(projects) == 1 {
			tenant = tenants[0]
			project = projects[0]
		}

		ch <- prometheus.MustNewConstMetric(
			appRouteInfo,
			prometheus.GaugeValue,
			1.0,
			appRouteCR.Name,
			tenant,
			project,
			vpc,
			appbox,
			string(appRouteCR.Status.Phase),
		)
	}
}
