package utils

import (
	"context"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
	openapicred "github.com/aliyun/credentials-go/credentials"
	awsconfig "github.com/aws/aws-sdk-go-v2/config"

	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/resourceworker/providers"
	"github.com/tidbcloud/observability/pkg/resourceworker/providers/alicloud"
	s3aws "github.com/tidbcloud/observability/pkg/resourceworker/providers/aws"
	azure "github.com/tidbcloud/observability/pkg/resourceworker/providers/azure"
	s3gcp "github.com/tidbcloud/observability/pkg/resourceworker/providers/gcp"
)

func PrepareS3Client(vendor string, region string, account string, resourceGroup string, storageAccount string) providers.S3Client {
	var s3 providers.S3Client = nil
	switch vendor {
	case string(constants.AWS):
		//we should  init aws config and client before start Observe
		cfg, err := awsconfig.LoadDefaultConfig(context.TODO())
		if err != nil {
			panic(err)
		}
		cfg.Region = region
		s3 = s3aws.NewS3(cfg)
	case string(constants.GCP):
		s3 = s3gcp.NewCloudStorage(account, region)
	case string(constants.Azure):
		cred, err := azidentity.NewDefaultAzureCredential(nil)
		if err != nil {
			panic(err)
		}
		s3, err = azure.NewBlobStorageClient(account, resourceGroup, storageAccount, cred)
		if err != nil {
			panic(err)
		}
	case string(constants.AliCloud):
		cred, err := openapicred.NewCredential(nil)
		if err != nil {
			panic(err)
		}
		provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) {
			cred, err := cred.GetCredential()
			if err != nil {
				return credentials.Credentials{}, err
			}
			return credentials.Credentials{
				AccessKeyID:     *cred.AccessKeyId,
				AccessKeySecret: *cred.AccessKeySecret,
				SecurityToken:   *cred.SecurityToken,
			}, nil
		})
		cfg := oss.LoadDefaultConfig().WithRegion(region).WithCredentialsProvider(provider)
		s3 = alicloud.NewS3(cfg, "")
	default:
		panic("unsupported vendor: " + vendor)
	}
	return s3
}
