/*
Copyright 2024.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package integrationtasks

import (
	"context"

	"github.com/go-logr/logr"
	"github.com/prometheus/client_golang/prometheus"
	observabilitypingcapcomv1 "github.com/tidbcloud/observability/api/regionalserver/resourceworker/v1"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/structs"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

var (
	IntegrationTaskInfo = prometheus.NewDesc(
		prometheus.BuildFQName("observability", "integration_task", "info"),
		"Information and status of integration task",
		[]string{"region", "task_name", "task_type", "user_id", "cluster_id", "tenant_id", "status"},
		nil)
)

type IntegrationTaskCollector struct {
	cli         client.Client
	log         logr.Logger
	serviceInfo structs.ServiceInfo
}

func NewIntegrationTaskCollector(cli client.Client, log logr.Logger, serviceInfo structs.ServiceInfo) *IntegrationTaskCollector {
	return &IntegrationTaskCollector{
		cli:         cli,
		log:         log,
		serviceInfo: serviceInfo,
	}
}

func (c *IntegrationTaskCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- IntegrationTaskInfo
}

func (c *IntegrationTaskCollector) Collect(ch chan<- prometheus.Metric) {
	ctx := context.Background()
	var taskList observabilitypingcapcomv1.IntegrationTaskList
	err := c.cli.List(ctx, &taskList)
	if err != nil {
		c.log.Error(err, "get integration task list failed!")
		return
	}

	for _, task := range taskList.Items {
		taskType := string(task.Spec.TaskType)
		status := string(task.Status.Phase)
		tenantID := task.Labels[constants.LabelTenantID]

		ch <- prometheus.MustNewConstMetric(
			IntegrationTaskInfo,
			prometheus.GaugeValue,
			1.0,
			c.serviceInfo.LogicalRegionName,
			task.Name,
			taskType,
			task.Labels[constants.LabelUserID],
			task.Spec.ClusterID,
			tenantID,
			status,
		)
	}
}
