package utils_oss

import (
	"ai_scheduler/internal/config"
	"bytes"
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-kratos/kratos/v2/log"
)

type Client struct {
	config config.Oss
	client *oss.Client
	bucket *oss.Bucket
}

// NewClient 初始化 OSS 客户端
func NewClient(cfg *config.Config) (*Client, error) {
	client, err := oss.New(cfg.Oss.Endpoint, cfg.Oss.AccessKey, cfg.Oss.SecretKey)
	if err != nil {
		return nil, fmt.Errorf("oss new client failed: %v", err)
	}

	bucket, err := client.Bucket(cfg.Oss.Bucket)
	if err != nil {
		return nil, fmt.Errorf("oss get bucket failed: %v", err)
	}

	return &Client{
		config: cfg.Oss,
		client: client,
		bucket: bucket,
	}, nil
}

// UploadBytes 上传字节数组到 OSS
// objectKey: OSS 中的文件路径，例如 "ai_scheduler/test.png"
// fileBytes: 文件内容
// 返回: 文件的访问 URL
func (c *Client) UploadBytes(objectKey string, fileBytes []byte) (string, error) {
	err := c.bucket.PutObject(objectKey, bytes.NewReader(fileBytes))
	if err != nil {
		log.Errorf("oss PutObject failed: %v", err)
		return "", err
	}

	// 构造返回 URL
	var url string
	if c.config.Domain != "" {
		url = fmt.Sprintf("%s/%s", c.config.Domain, objectKey)
	} else {
		// 这里简单处理协议头
		url = fmt.Sprintf("https://%s.%s/%s", c.config.Bucket, c.config.Endpoint, objectKey)
	}
	return url, nil
}
