package com.zhentao.util;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.UUID;

/**
 * 反馈图片上传工具类
 */
@Slf4j
@Component
public class FeedbackUploadUtil {
    
    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private com.zhentao.config.MinioConfig minioConfig;
    
    /**
     * 初始化：确保桶存在并设置为公共访问
     */
    @PostConstruct
    public void init() {
        try {
            String bucketName = minioConfig.getBucketName();
            
            // 检查桶是否存在
            boolean exists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );
            
            if (!exists) {
                log.info("MinIO桶不存在，开始创建: {}", bucketName);
                
                // 创建桶
                minioClient.makeBucket(
                    MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build()
                );
                
                log.info("✅ MinIO桶创建成功: {}", bucketName);
                
                // 设置桶为公共访问（允许匿名读取）
                String policy = String.format(
                    "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::%s/*\"]}]}",
                    bucketName
                );
                
                minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(policy)
                        .build()
                );
                
                log.info("✅ MinIO桶权限设置成功（公共读取）: {}", bucketName);
            } else {
                log.info("MinIO桶已存在: {}", bucketName);
            }
            
        } catch (Exception e) {
            log.error("❌ 初始化MinIO失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 上传反馈图片到MinIO
     * 
     * @param inputStream 图片文件输入流
     * @param originalFilename 原始文件名
     * @param contentType 文件内容类型
     * @return MinIO中的对象URL（永久有效，不使用预签名）
     */
    public String uploadFeedbackImage(InputStream inputStream, String originalFilename, String contentType) {
        try {
            // 1. 生成唯一文件名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "feedback_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "") + suffix;
            
            // 2. 构建对象路径
            String objectName = minioConfig.getUserFeedbackFolder() + "/" + fileName;
            
            log.info("开始上传反馈图片到MinIO: objectName={}", objectName);
            
            // 3. 上传到MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .stream(inputStream, -1, 10485760) // 10MB chunk size
                    .contentType(contentType)
                    .build()
            );
            
            // 4. 生成公共访问URL（不使用预签名，永久有效）
            String imageUrl = String.format("%s/%s/%s", 
                minioConfig.getEndpoint(),
                minioConfig.getBucketName(),
                objectName);
            
            log.info("✅ 反馈图片上传成功: {}", imageUrl);
            return imageUrl;
            
        } catch (Exception e) {
            log.error("❌ 上传反馈图片失败: {}", e.getMessage(), e);
            return null;
        }
    }
}