/**
 * 파일 업로드 미들웨어 (multer)
 */

const multer = require('multer');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '..', 'uploads'));
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const uniqueName = `workplace-layout-${Date.now()}-${crypto.randomInt(100000000, 999999999)}${ext}`;
    cb(null, uniqueName);
  }
});

const fileFilter = (req, file, cb) => {
  const allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (allowed.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('허용되지 않는 파일 형식입니다. (JPEG, PNG, GIF, WebP만 가능)'), false);
  }
};

const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }
});

// 소모품 사진 업로드
const consumablesDir = path.join(__dirname, '..', 'uploads', 'consumables');
try { if (!fs.existsSync(consumablesDir)) { fs.mkdirSync(consumablesDir, { recursive: true }); } } catch (e) { console.warn('consumables 디렉토리 생성 실패 (Dockerfile에서 미리 생성 필요):', e.message); }

const consumableStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, consumablesDir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const uniqueName = `consumable-${Date.now()}-${crypto.randomInt(100000000, 999999999)}${ext}`;
    cb(null, uniqueName);
  }
});

const consumableUpload = multer({
  storage: consumableStorage,
  fileFilter,
  limits: { fileSize: 5 * 1024 * 1024 }
});

module.exports = upload;
module.exports.consumableUpload = consumableUpload;
