package upload

import (
	"mime/multipart"
	"path"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// Aliyun 阿里云OSS
type Aliyun struct {
	Endpoint        string
	AccessKeyID     string
	AccessKeySecret string
	BucketName      string
	BucketURL       string
	BasePath        string
}

// NewAliyun 创建阿里云OSS
func NewAliyun(endpoint, accessKeyID, accessKeySecret, bucketName, bucketURL, basePath string) *Aliyun {
	return &Aliyun{
		Endpoint:        endpoint,
		AccessKeyID:     accessKeyID,
		AccessKeySecret: accessKeySecret,
		BucketName:      bucketName,
		BucketURL:       bucketURL,
		BasePath:        basePath,
	}
}

// UploadFile 上传文件
func (a *Aliyun) UploadFile(file *multipart.FileHeader) (string, string, error) {
	client, err := oss.New(a.Endpoint, a.AccessKeyID, a.AccessKeySecret)
	if err != nil {
		return "", "", err
	}

	bucket, err := client.Bucket(a.BucketName)
	if err != nil {
		return "", "", err
	}

	// 生成文件名和路径
	fileName := GenerateFileName(file.Filename)
	filePath := GeneratePath(a.BasePath)
	key := path.Join(filePath, fileName)

	// 打开文件
	src, err := file.Open()
	if err != nil {
		return "", "", err
	}
	defer src.Close()

	// 上传
	if err = bucket.PutObject(key, src); err != nil {
		return "", "", err
	}

	// 返回访问URL和key
	accessURL := a.BucketURL + "/" + key
	return accessURL, key, nil
}

// DeleteFile 删除文件
func (a *Aliyun) DeleteFile(key string) error {
	client, err := oss.New(a.Endpoint, a.AccessKeyID, a.AccessKeySecret)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(a.BucketName)
	if err != nil {
		return err
	}

	return bucket.DeleteObject(key)
}
