package com.zhentao.controller;

import com.zhentao.common.Result;
import com.zhentao.service.MinioService;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * MinIO测试控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/test/minio")
@CrossOrigin(origins = "*", maxAge = 3600)
public class MinioTestController {
    
    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private MinioService minioService;
    
    @Value("${minio.endpoint}")
    private String endpoint;
    
    @Value("${minio.bucketName}")
    private String bucketName;
    
    /**
     * 测试MinIO连接
     */
    @GetMapping("/connection")
    public Result<Map<String, Object>> testConnection() {
        try {
            log.info("========== 测试MinIO连接 ==========");
            log.info("Endpoint: {}", endpoint);
            log.info("BucketName: {}", bucketName);
            
            Map<String, Object> data = new HashMap<>();
            data.put("endpoint", endpoint);
            data.put("bucketName", bucketName);
            
            // 测试连接 - 列出所有bucket
            int bucketsCount = minioClient.listBuckets().size();
            data.put("bucketsCount", bucketsCount);
            
            // 检查目标bucket是否存在
            boolean exists = minioClient.bucketExists(
                BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build()
            );
            data.put("targetBucketExists", exists);
            data.put("status", "连接成功");
            
            log.info("✓ MinIO连接测试成功");
            log.info("  - 发现 {} 个bucket", bucketsCount);
            log.info("  - 目标bucket存在: {}", exists);
            
            return Result.success("MinIO连接测试成功", data);
            
        } catch (Exception e) {
            log.error("MinIO连接测试失败", e);
            return Result.error("连接失败：" + e.getMessage());
        }
    }
    
    /**
     * 确保bucket存在
     */
    @PostMapping("/ensure-bucket")
    public Result<String> ensureBucket() {
        try {
            log.info("========== 检查并创建Bucket ==========");
            minioService.ensureBucketExists();
            return Result.success("Bucket已就绪");
        } catch (Exception e) {
            log.error("Bucket操作失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
}

