package aws

import (
	"context"
	"fmt"

	ec2api "github.com/aws/aws-sdk-go-v2/service/ec2"
	ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
)

// FindReusableVPCEndpointID tries to find a reusable vpc endpoint using AWS native API.
// The reusable vpc endpoint should have the same service name and vpc id as given.
func FindReusableVPCEndpointID(ctx context.Context, cli *ec2api.Client, endpointType, endpointServiceName, vpcID string) (string, error) {
	output, err := cli.DescribeVpcEndpoints(ctx, &ec2api.DescribeVpcEndpointsInput{})
	if err != nil {
		return "", fmt.Errorf("failed to describe vpc endpoints: %w", err)
	}

	for _, endpoint := range output.VpcEndpoints {
		if isVPCEndpointReusable(&endpoint, endpointType, endpointServiceName, vpcID) {
			return *endpoint.VpcEndpointId, 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 not be in deleting state.
func isVPCEndpointReusable(endpoint *ec2types.VpcEndpoint, endpointType, serviceName, vpcID string) bool {
	if endpoint.ServiceName == nil || *endpoint.ServiceName != serviceName {
		return false
	}
	if endpoint.VpcId == nil || *endpoint.VpcId != vpcID {
		return false
	}
	if string(endpoint.VpcEndpointType) != endpointType {
		return false
	}
	// Check if not in deleting state
	if endpoint.State == ec2types.StateDeleted || endpoint.State == ec2types.StateDeleting {
		return false
	}
	return true
}
