package core

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

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

// NewCosClient 根据配置创建 COS 客户端。
func NewCosClient(cfg *config.Config) (*cos.Client, error) {
	bucketURL, err := url.Parse(fmt.Sprintf("https://%s.cos.%s.myqcloud.com", cfg.Bucket, cfg.Region))
	if err != nil {
		return nil, fmt.Errorf("解析存储桶URL失败: %w", err)
	}

	b := &cos.BaseURL{BucketURL: bucketURL}
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  cfg.SecretId,
			SecretKey: cfg.SecretKey,
		},
	})

	return client, nil
}

// ListAllFiles 列出 COS 中所有匹配前缀的文件。
func ListAllFiles(ctx context.Context, client *cos.Client, prefix string) ([]FileInfo, error) {
	var allFiles []FileInfo
	var marker string

	for {
		opt := &cos.BucketGetOptions{Prefix: prefix, MaxKeys: MaxKeysPerRequest, Marker: marker}
		v, _, err := client.Bucket.Get(ctx, opt)
		if err != nil {
			return nil, err
		}

		for _, item := range v.Contents {
			// 只处理非目录对象
			if !strings.HasSuffix(item.Key, "/") {
				allFiles = append(allFiles, FileInfo{
					Key:          item.Key,
					Size:         item.Size,
					LastModified: item.LastModified,
				})
			}
		}

		if !v.IsTruncated {
			break
		}
		marker = v.NextMarker
	}
	return allFiles, nil
}
