package controllers

import (
	"context"
	"fmt"

	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"github.com/tidbcloud/infra-provider/pkg/util"
)

// CheckRegionalLabel ensures the objects contains regional label if it resides in the region.
// It ignores objects with regional label and returns error if the object belongs other region.
func CheckRegionalLabel(ctx context.Context, c *cloudv1.Cluster, obj client.Object, cli client.Client, region string) error {
	if util.ContainsRegionLabel(obj) {
		return nil
	}
	ok, err := util.CheckClusterRegion(ctx, cli, c, region)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("cluster %s is not in region %s", c.Name, region)
	}

	// update the object with the regional label
	_, err = controllerutil.CreateOrUpdate(ctx, cli, obj, func() error {
		util.EnsureRegion(obj, region)
		return nil
	})
	return err
}
