const { client, BUCKET, publicUrl } = require('../config/minio');
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');
const path = require('path');

const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
const BIN_TYPES   = new Set(['application/octet-stream']);

// 이미지 업로드: WebP 변환 + 리사이즈
async function uploadImage(buffer, originalName, folder = 'images') {
  const id = uuidv4();
  const objectName = `${folder}/${id}.webp`;
  const thumbName  = `${folder}/${id}_thumb.webp`;

  const [main, thumb] = await Promise.all([
    sharp(buffer)
      .resize(1920, 1080, { fit: 'inside', withoutEnlargement: true })
      .webp({ quality: 82 })
      .toBuffer(),
    sharp(buffer)
      .resize(400, 300, { fit: 'cover' })
      .webp({ quality: 70 })
      .toBuffer(),
  ]);

  await Promise.all([
    client.putObject(BUCKET, objectName, main, main.length, { 'Content-Type': 'image/webp' }),
    client.putObject(BUCKET, thumbName, thumb, thumb.length, { 'Content-Type': 'image/webp' }),
  ]);

  return {
    url:          publicUrl(objectName),
    thumbnailUrl: publicUrl(thumbName),
    fileSize:     main.length,
    mimeType:     'image/webp',
  };
}

// 일반 파일 업로드 (bin, stl, pdf 등)
async function uploadRaw(buffer, originalName, mimeType, folder = 'files') {
  const ext        = path.extname(originalName).toLowerCase();
  const id         = uuidv4();
  const objectName = `${folder}/${id}${ext}`;

  await client.putObject(BUCKET, objectName, buffer, buffer.length, {
    'Content-Type': mimeType || 'application/octet-stream',
  });

  return {
    url:      publicUrl(objectName),
    fileSize: buffer.length,
    mimeType: mimeType || 'application/octet-stream',
  };
}

// 오브젝트 삭제
async function deleteObject(url) {
  try {
    // URL에서 object name 추출: http://host:port/bucket/path/to/file
    const parts = new URL(url).pathname.split('/').slice(2); // bucket 이후
    const objectName = parts.join('/');
    await client.removeObject(BUCKET, objectName);
  } catch (err) {
    console.error('MinIO delete error:', err.message);
  }
}

module.exports = { uploadImage, uploadRaw, deleteObject, IMAGE_TYPES };
