package oss_core

import (
	"context"
	"fmt"
	"io"
	"mime/multipart"
	"path/filepath"
	"strings"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/common/utils/hash"
)

type AliyunUploader struct {
	bucket *oss.Bucket
	config *file.StorageConfigInfo
}

func NewAliyunUploader(conf *file.StorageConfigInfo) (Uploader, error) {
	client, err := oss.New(conf.Endpoint, conf.AccessKeyId, conf.AccessKeySecret)
	if err != nil {
		return nil, err
	}
	bucket, err := client.Bucket(conf.BucketName)
	if err != nil {
		return nil, err
	}
	return &AliyunUploader{
		bucket: bucket,
		config: conf,
	}, nil
}

func (a *AliyunUploader) UploadFile(ctx context.Context, file multipart.File, fileHeader *multipart.FileHeader) (string, string, error) {
	ext := filepath.Ext(fileHeader.Filename)
	filename := hash.MD5([]byte(strings.TrimSuffix(fileHeader.Filename, ext))) + ext
	timestr := fmt.Sprintf("%d", time.Now().UnixMicro())
	objectKey := time.Now().Format("2006-01-02") + "/" + timestr + "-" + filename

	err := a.bucket.PutObject(objectKey, file)
	if err != nil {
		return "", "", fmt.Errorf("上传阿里云OSS失败: %v", err)
	}

	url := a.config.BucketUrl + "/" + objectKey
	return url, objectKey, nil
}

func (a *AliyunUploader) DeleteFile(ctx context.Context, key string) error {
	return a.bucket.DeleteObject(key)
}

func (a *AliyunUploader) DownloadFile(ctx context.Context, key string) (io.ReadCloser, error) {
	return a.bucket.GetObject(key)
}
