package oss

import (
	"context"
	"nms_nbi/src/framework/config"
	"nms_nbi/src/framework/logger"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

// OInitConm OSS初始配置连接实例
var OInitConm *minio.Client

// InitConfig 连接OSS实例
func InitConfig() {
	// 读取数据源配置
	bucketname := config.Get("cxy.oss.bucketname").(string)
	endpoint := config.Get("cxy.oss.endpoint").(string)
	useSSL := config.Get("cxy.oss.useSSL").(bool)
	accessKeyID := config.Get("cxy.oss.accessKeyID").(string)
	secretAccessKey := config.Get("cxy.oss.secretAccessKey").(string)

	// 初始minio客户端对象
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		logger.Fatalf("minio %s client err %v", endpoint, err)
	}

	// 检查存储桶是否存在可用
	found, err := minioClient.BucketExists(context.Background(), bucketname)
	if err != nil {
		logger.Fatalf("minio %s bucket [%s] exists err %v", endpoint, bucketname, err)
	}
	if !found {
		logger.Fatalf("minio %s bucket [%s] not found err %v", endpoint, bucketname, err)
	}
	logger.Infof("minio  %s bucket [%s] exists", endpoint, bucketname)
	OInitConm = minioClient
}

// FileUploadFileByFilePath 文件上传-文件绝对路径
func FileUploadFileByFilePath(filePath, newFileName string) (minio.UploadInfo, error) {
	bucketname := config.Get("cxy.oss.bucketname").(string)
	contentType := "application/octet-stream"
	// Upload the test file with FPutObject
	ctx := context.Background()
	return OInitConm.FPutObject(ctx, bucketname, newFileName, filePath, minio.PutObjectOptions{ContentType: contentType})
}
