package ali

import (
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
	"go.ipao.vip/atom/container"
	"go.ipao.vip/atom/opt"
)

const DefaultPrefix = "Ali"

func DefaultProvider() container.ProviderContainer {
	return container.ProviderContainer{
		Provider: Provide,
		Options: []opt.Option{
			opt.Prefix(DefaultPrefix),
		},
	}
}

type Config struct {
	AccessKeyId     string
	AccessKeySecret string
	Bucket          string
	Region          string
	Host            *string
	CallbackURL     string
}

func Provide(opts ...opt.Option) error {
	o := opt.New(opts...)
	var config Config
	if err := o.UnmarshalConfig(&config); err != nil {
		return err
	}

	return container.Container.Provide(func() (*OSSClient, error) {
		cred := credentials.NewStaticCredentialsProvider(config.AccessKeyId, config.AccessKeySecret)

		cfg := oss.LoadDefaultConfig().
			WithCredentialsProvider(cred).
			WithRegion(config.Region).
			WithUseCName(true).
			WithEndpoint(*config.Host)

		cfgInternal := oss.LoadDefaultConfig().
			WithCredentialsProvider(cred).
			WithRegion(config.Region)

		return &OSSClient{
			client:         oss.NewClient(cfg),
			internalClient: oss.NewClient(cfgInternal),
			config:         &config,
		}, nil
	}, o.DiOptions()...)
}
