const Minio = require('minio');

const config = {
  endPoint: process.env.MINIO_ENDPOINT || 'localhost',
  port: parseInt(process.env.MINIO_PORT) || 9000,
  useSSL: process.env.MINIO_USE_SSL === 'true',
  accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
  secretKey: process.env.MINIO_SECRET_KEY || 'minioadmin'
};

console.log('MinIO 配置:', {
  ...config,
  secretKey: '***' // 隐藏密钥
});

const client = new Minio.Client(config);

const BUCKET = process.env.MINIO_BUCKET || 'quanyoumi';

// 确保 bucket 存在
const ensureBucket = async () => {
  try {
    console.log(`检查 bucket: ${BUCKET}`);
    const exists = await client.bucketExists(BUCKET);
    console.log(`Bucket ${BUCKET} 存在:`, exists);
    
    if (!exists) {
      console.log(`创建 bucket: ${BUCKET}`);
      await client.makeBucket(BUCKET);
      
      // 设置公开读取策略
      const policy = JSON.stringify({
        Version: '2012-10-17',
        Statement: [{
          Effect: 'Allow',
          Principal: { AWS: ['*'] },
          Action: ['s3:GetObject'],
          Resource: [`arn:aws:s3:::${BUCKET}/*`]
        }]
      });
      await client.setBucketPolicy(BUCKET, policy);
      console.log(`Bucket ${BUCKET} 创建成功并设置为公开读取`);
    }
  } catch (error) {
    console.error('ensureBucket 错误:', error);
    throw error;
  }
};

// 上传 buffer 到 MinIO，返回公开访问 URL
const uploadBuffer = async (buffer, filename, mimetype) => {
  try {
    console.log(`开始上传文件: ${filename}, 大小: ${buffer.length} bytes`);
    await ensureBucket();
    
    await client.putObject(BUCKET, filename, buffer, buffer.length, { 'Content-Type': mimetype });
    console.log(`文件上传成功: ${filename}`);
    
    // 如果配置了公开 URL 就用，否则用 endpoint 拼接
    const publicUrl = process.env.MINIO_PUBLIC_URL;
    if (publicUrl) {
      return `${publicUrl}/${BUCKET}/${filename}`;
    }
    
    const protocol = process.env.MINIO_USE_SSL === 'true' ? 'https' : 'http';
    const endpoint = process.env.MINIO_ENDPOINT || 'localhost';
    const port = process.env.MINIO_PORT || 9000;
    return `${protocol}://${endpoint}:${port}/${BUCKET}/${filename}`;
  } catch (error) {
    console.error('uploadBuffer 错误:', error);
    throw error;
  }
};

// 从 MinIO 删除文件
const deleteFile = async (filename) => {
  try {
    console.log(`开始删除文件: ${filename}`);
    await client.removeObject(BUCKET, filename);
    console.log(`文件删除成功: ${filename}`);
    return true;
  } catch (error) {
    console.error('deleteFile 错误:', error);
    throw error;
  }
};

module.exports = { client, BUCKET, uploadBuffer, deleteFile };
