const Minio = require('minio');

const client = new Minio.Client({
  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,
  secretKey: process.env.MINIO_SECRET_KEY,
});

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

async function ensureBucket() {
  const exists = await client.bucketExists(BUCKET);
  if (!exists) {
    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(`MinIO bucket "${BUCKET}" created`);
  }
}

// 파일 업로드 후 공개 URL 반환
function publicUrl(objectName) {
  const proto = process.env.MINIO_USE_SSL === 'true' ? 'https' : 'http';
  const host  = process.env.MINIO_ENDPOINT || 'localhost';
  const port  = process.env.MINIO_PORT || '9000';
  return `${proto}://${host}:${port}/${BUCKET}/${objectName}`;
}

module.exports = { client, BUCKET, ensureBucket, publicUrl };
