package obs

import (
	awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
	clitypes "gitlink.org.cn/cloudream/jcs-pub/client/types"
	"gitlink.org.cn/cloudream/jcs-pub/common/pkgs/storage/s3"
	"gitlink.org.cn/cloudream/jcs-pub/common/pkgs/storage/types"
	cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types"
)

type ShardStore struct {
	*s3.ShardStore
	cred *cortypes.OBSCred
}

func NewShardStore(detail *clitypes.UserSpaceDetail, cred *cortypes.OBSCred, s3Cli *awss3.Client, bkt string) (*ShardStore, error) {
	sd := ShardStore{
		cred: cred,
	}

	var err error
	sd.ShardStore, err = s3.NewShardStore(detail, s3Cli, bkt, s3.ShardStoreOption{
		UseAWSSha256: false,
	})
	if err != nil {
		return nil, err
	}

	return &sd, nil
}

func (s *ShardStore) HTTPBypassRead(fileHash clitypes.FileHash) (types.HTTPRequest, error) {
	cli, err := obs.New(s.cred.AK, s.cred.SK, s.cred.Endpoint)
	if err != nil {
		return types.HTTPRequest{}, err
	}

	getSigned, err := cli.CreateSignedUrl(&obs.CreateSignedUrlInput{
		Method:  "GET",
		Bucket:  s.Bucket,
		Key:     s.GetFilePathFromHash(fileHash),
		Expires: 3600,
	})
	if err != nil {
		return types.HTTPRequest{}, err
	}

	return types.HTTPRequest{
		URL:    getSigned.SignedUrl,
		Method: "GET",
	}, nil
}
