package upload

import (
	"mime/multipart"
	"path"

	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)

// HuaweiObs 华为云OBS
type HuaweiObs struct {
	Path      string
	Bucket    string
	Endpoint  string
	AccessKey string
	SecretKey string
}

// NewHuaweiObs 创建华为云OBS
func NewHuaweiObs(obsPath, bucket, endpoint, accessKey, secretKey string) *HuaweiObs {
	return &HuaweiObs{
		Path:      obsPath,
		Bucket:    bucket,
		Endpoint:  endpoint,
		AccessKey: accessKey,
		SecretKey: secretKey,
	}
}

func (h *HuaweiObs) getClient() (*obs.ObsClient, error) {
	return obs.New(h.AccessKey, h.SecretKey, h.Endpoint)
}

// UploadFile 上传文件
func (h *HuaweiObs) UploadFile(file *multipart.FileHeader) (string, string, error) {
	client, err := h.getClient()
	if err != nil {
		return "", "", err
	}
	defer client.Close()

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

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

	// 上传
	input := &obs.PutObjectInput{}
	input.Bucket = h.Bucket
	input.Key = key
	input.Body = src
	_, err = client.PutObject(input)
	if err != nil {
		return "", "", err
	}

	// 返回访问URL和key
	accessURL := "https://" + h.Bucket + "." + h.Endpoint + "/" + key
	return accessURL, key, nil
}

// DeleteFile 删除文件
func (h *HuaweiObs) DeleteFile(key string) error {
	client, err := h.getClient()
	if err != nil {
		return err
	}
	defer client.Close()

	input := &obs.DeleteObjectInput{}
	input.Bucket = h.Bucket
	input.Key = key
	_, err = client.DeleteObject(input)
	return err
}
