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

// Sharp is optional — may fail on shared hosting
let sharp;
try {
  sharp = require('sharp');
} catch (e) {
  console.warn('⚠️ sharp not available, image compression disabled. Upload will save originals.');
}

// Standard upload — disk storage, 5MB, images + pdf
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir = path.join(__dirname, '..', 'uploads');
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowedExt = /jpeg|jpg|png|gif|webp|pdf/;
    const allowedMime = /^(image\/(jpeg|png|gif|webp)|application\/pdf)$/;
    const extOk = allowedExt.test(path.extname(file.originalname).toLowerCase());
    const mimeOk = allowedMime.test(file.mimetype);
    if (extOk && mimeOk) cb(null, true);
    else cb(new Error('Tipe file tidak diizinkan. Hanya JPG, PNG, GIF, WEBP, dan PDF.'));
  }
});

// Galeri upload — memory storage for sharp processing, 10MB, images only
const galeriUpload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowedExt = /jpeg|jpg|png|gif|webp/;
    const allowedMime = /^image\/(jpeg|png|gif|webp)$/;
    const extOk = allowedExt.test(path.extname(file.originalname).toLowerCase());
    const mimeOk = allowedMime.test(file.mimetype);
    if (extOk && mimeOk) cb(null, true);
    else cb(new Error('Hanya file gambar (JPG, PNG, GIF, WEBP) yang diizinkan'));
  }
});

// Image compression helper — fallback to saving original if sharp unavailable
async function compressImage(buffer, originalName) {
  const dir = path.join(__dirname, '..', 'uploads');
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

  if (sharp) {
    // Compress with sharp
    const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.webp`;
    const outputPath = path.join(dir, filename);
    await sharp(buffer)
      .resize({ width: 1920, height: 1920, fit: 'inside', withoutEnlargement: true })
      .webp({ quality: 80 })
      .toFile(outputPath);
    return { filename, url: `/uploads/${filename}` };
  } else {
    // Fallback: save original file
    const ext = path.extname(originalName).toLowerCase() || '.jpg';
    const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`;
    const outputPath = path.join(dir, filename);
    fs.writeFileSync(outputPath, buffer);
    return { filename, url: `/uploads/${filename}` };
  }
}

module.exports = { upload, galeriUpload, compressImage };

