package infra

import (
	"context"
	"fmt"
	"time"

	"github.com/tidbcloud/aws-shared-provider/pkg/scheme"
	labelsutil "github.com/tidbcloud/aws-shared-provider/pkg/utils/labels"
	cloudv1 "github.com/tidbcloud/infra-api/api/v1"
	"k8s.io/apimachinery/pkg/labels"
	apitypes "k8s.io/apimachinery/pkg/types"
	"k8s.io/utils/ptr"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/cache"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/cluster"
)

type infraApiImpl struct {
	infraApiKubeClient client.Client
	cluster            cluster.Cluster
}

func NewInfraAPI(ctx context.Context, conf *InfraConfig) (InfraAPI, error) {
	var err error
	infraCluster, err := cluster.New(conf.Rest, func(clusterOptions *cluster.Options) {
		clusterOptions.Scheme = scheme.Scheme
		selector := labels.Set(map[string]string{
			cloudv1.ProviderTypeLabel: conf.CloudProviderType,
		})
		if conf.KubeClusterName != "" {
			selector[labelsutil.LabelKeyKubernetesCluster] = conf.KubeClusterName
		}
		clusterOptions.Cache = cache.Options{
			SyncPeriod: ptr.To[time.Duration](0),
			ByObject: map[client.Object]cache.ByObject{
				&cloudv1.Branch{}: {
					Label:                 selector.AsSelector(),
					UnsafeDisableDeepCopy: ptr.To(true),
				},
			},
		}
	})
	if err != nil {
		return nil, err
	}

	if err := infraCluster.GetFieldIndexer().IndexField(ctx, &cloudv1.Branch{},
		"status.fromProvider.keyspaceToken", func(obj client.Object) []string {
			b := obj.(*cloudv1.Branch)
			clusterStatus, err := b.AwsFreeTierClusterStatusFromBranch()
			if err != nil {
				ctrl.Log.Error(err, "get keyspace token", "branch", b.Name)
				return nil
			}
			if clusterStatus.KeyspaceToken != "" {
				return []string{clusterStatus.KeyspaceToken}
			}
			return nil
		}); err != nil {
		return nil, fmt.Errorf("unable to add index for branch token: %w", err)
	}

	return &infraApiImpl{infraApiKubeClient: infraCluster.GetClient(), cluster: infraCluster}, nil
}

func (i *infraApiImpl) GetBranch(ctx context.Context, namespace, name string) (*cloudv1.Branch, error) {
	infraBranch := &cloudv1.Branch{}
	if err := i.infraApiKubeClient.Get(ctx, client.ObjectKey{Name: name, Namespace: namespace}, infraBranch); err != nil {
		return nil, err
	}
	return infraBranch, nil
}

func (i *infraApiImpl) GetBranchWithToken(ctx context.Context, token string) (*cloudv1.Branch, error) {
	var bls cloudv1.BranchList
	if err := i.infraApiKubeClient.List(ctx, &bls, client.MatchingFields(map[string]string{
		"status.fromProvider.keyspaceToken": token,
	})); err != nil {
		return nil, err
	}
	if len(bls.Items) == 0 {
		return nil, ErrNotFound
	}
	return &bls.Items[0], nil
}

func (i *infraApiImpl) PatchBranch(ctx context.Context, namespace, name string, data []byte) (*cloudv1.Branch, error) {
	branch := &cloudv1.Branch{ObjectMeta: ctrl.ObjectMeta{Namespace: namespace, Name: name}}
	return branch, i.infraApiKubeClient.Patch(ctx, branch, client.RawPatch(apitypes.MergePatchType, data))
}

func (i *infraApiImpl) Start(ctx context.Context) error {
	return i.cluster.Start(ctx)
}

func (i *infraApiImpl) WaitForCacheSync(ctx context.Context) bool {
	return i.cluster.GetCache().WaitForCacheSync(ctx)
}
