import fs from 'fs';
import multer from 'multer';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const baseUploadDir = path.join(__dirname, '..', 'uploads', 'tree_images');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const fieldName = file.fieldname;
    const fieldDir = path.join(baseUploadDir, fieldName);

    if (!fs.existsSync(fieldDir)) {
      fs.mkdirSync(fieldDir, { recursive: true });
    }
    cb(null, fieldDir);
  },
  filename: (req, file, cb) => {
    const timestamp = Date.now();
    const ext = path.extname(file.originalname);
    let filename;

    switch (file.fieldname) {
      case 'image':
        filename = `leaf_${timestamp}${ext}`;
        break;
      case 'image_leaves':
        filename = `bark_${timestamp}${ext}`;
        break;
      case 'image3':
        filename = `full_${timestamp}${ext}`;
        break;
      case 'image4':
        filename = `full_${timestamp}${ext}`;
        break;
      default:
        filename = `${file.fieldname}_${timestamp}${ext}`;
    }

    cb(null, filename);
  }
});

const fileFilter = (req, file, cb) => {
  const filetypes = /jpeg|jpg|png/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (extname && mimetype) {
    cb(null, true);
  } else {
    cb(new Error('Only images are allowed'));
  }
};

// ✅ Add limits here — allow up to 20 MB per file
export const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 20 * 1024 * 1024 } // 20 MB
});

export const uploadMultipleFields = (fieldsArray) => upload.fields(fieldsArray);
