package central

import (
	"context"
	"errors"
	"fmt"
	"net/url"
	"strings"

	"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)

func checkAzureBlobStorageAccess(ctx context.Context, blobUri, sasToken string) error {
	u, err := url.Parse(blobUri)
	if err != nil {
		return fmt.Errorf("parse blob uri error: %w", err)
	}

	blobPath := strings.Trim(u.Path, "/")
	i := strings.Index(blobPath, "/")
	var containerName string
	if i == -1 {
		containerName = blobPath
	} else {
		containerName = blobPath[:i]
	}
	if containerName == "" {
		return errors.New("can't find container name from uri")
	}

	u.Path = "/"
	serviceEndpoint := u.String()

	serviceUrl := fmt.Sprintf("%s?%s", serviceEndpoint, sasToken)
	cli, err := azblob.NewClientWithNoCredential(serviceUrl, nil)
	if err != nil {
		return fmt.Errorf("new az blob client with service endpoint %s error: %w", serviceEndpoint, err)
	}

	maxResult := int32(10)
	pager := cli.NewListBlobsFlatPager(containerName, &azblob.ListBlobsFlatOptions{
		MaxResults: &maxResult,
	})
	if pager.More() {
		_, err := pager.NextPage(ctx)
		if err != nil {
			return fmt.Errorf("list blobs of container %s error: %w", containerName, err)
		}
	}
	return nil
}
