package upload

import (
	"context"
	"fmt"
	"mime/multipart"
	"net/http"
	"net/url"
	"path"

	"github.com/tencentyun/cos-go-sdk-v5"
)

// Tencent 腾讯云COS
type Tencent struct {
	Bucket     string
	Region     string
	SecretID   string
	SecretKey  string
	BaseURL    string
	PathPrefix string
}

// NewTencent 创建腾讯云COS
func NewTencent(bucket, region, secretID, secretKey, baseURL, pathPrefix string) *Tencent {
	return &Tencent{
		Bucket:     bucket,
		Region:     region,
		SecretID:   secretID,
		SecretKey:  secretKey,
		BaseURL:    baseURL,
		PathPrefix: pathPrefix,
	}
}

func (t *Tencent) getClient() *cos.Client {
	u, _ := url.Parse(fmt.Sprintf("https://%s.cos.%s.myqcloud.com", t.Bucket, t.Region))
	b := &cos.BaseURL{BucketURL: u}
	return cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  t.SecretID,
			SecretKey: t.SecretKey,
		},
	})
}

// UploadFile 上传文件
func (t *Tencent) UploadFile(file *multipart.FileHeader) (string, string, error) {
	client := t.getClient()

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

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

	// 上传
	_, err = client.Object.Put(context.Background(), key, src, nil)
	if err != nil {
		return "", "", err
	}

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

// DeleteFile 删除文件
func (t *Tencent) DeleteFile(key string) error {
	client := t.getClient()
	_, err := client.Object.Delete(context.Background(), key)
	return err
}
