package alicloudupbound

import (
	"context"
	"fmt"

	aliplv1alpha1 "github.com/crossplane-contrib/provider-upjet-alibabacloud/apis/privatelink/v1alpha1"
	xpv1 "github.com/crossplane/crossplane-runtime/apis/common/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// FindReusableVPCEndpointName tries to find a reusable vpc endpoint, so we do not need to create a new one.
// The reusable vpc endpoint should have the same service name and vpc id as given.
func FindReusableVPCEndpointName(ctx context.Context, cli client.Client, endpointType, endpointServiceName, vpcID string) (string, error) {
	var endpointList aliplv1alpha1.VpcEndpointList
	if err := cli.List(ctx, &endpointList); err != nil {
		return "", fmt.Errorf("failed to list vpc endpoint: %w", err)
	}
	for i := range endpointList.Items {
		endpoint := &endpointList.Items[i]
		if isVPCEndpointReusable(endpoint, endpointType, endpointServiceName, vpcID) {
			return endpointList.Items[i].Name, nil
		}
	}
	return "", nil
}

// isVPCEndpointReusable checks whether the given vpc endpoint is reusable.
// A reusable vpc endpoint should have the same service name and vpc id as given,
// and should be in an available state.
func isVPCEndpointReusable(endpoint *aliplv1alpha1.VpcEndpoint, endpointType, serviceName, vpcID string) bool {
	if endpoint.Spec.ForProvider.ServiceName == nil || *endpoint.Spec.ForProvider.ServiceName != serviceName {
		return false
	}
	if endpoint.Spec.ForProvider.VPCID == nil || *endpoint.Spec.ForProvider.VPCID != vpcID {
		return false
	}
	if endpoint.Spec.ForProvider.EndpointType == nil || *endpoint.Spec.ForProvider.EndpointType != endpointType {
		return false
	}

	condition := endpoint.Status.GetCondition(xpv1.TypeReady)
	if condition.Reason == xpv1.ReasonDeleting {
		return false
	}
	return true
}
