import multer from 'multer';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import fs from 'fs';

const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR || '../uploads');
const TEAM_DIR = path.join(UPLOAD_DIR, 'team');

if (!fs.existsSync(TEAM_DIR)) {
  fs.mkdirSync(TEAM_DIR, { recursive: true });
}

const storage = multer.diskStorage({
  destination(_req, _file, cb) {
    cb(null, TEAM_DIR);
  },
  filename(_req, file, cb) {
    const ext = path.extname(file.originalname).toLowerCase() || '.jpg';
    cb(null, `${uuidv4()}${ext}`);
  },
});

export const uploadTeamPhoto = multer({
  storage,
  fileFilter(_req, file, cb) {
    if (/^image\/(jpeg|jpg|png|gif|webp)$/i.test(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('JPEG, PNG, GIF, WebP 이미지만 업로드할 수 있습니다.'));
    }
  },
});
