import multer from 'multer';
import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import { Jimp } from 'jimp';

const UPLOAD_ROOT = path.resolve('public/uploads');

function ensureDir(dir) {
  fs.mkdirSync(dir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const angkatanId = req.params.id || req.params.angkatanId || 'misc';
    const dir = path.join(UPLOAD_ROOT, `angkatan-${angkatanId}`);
    ensureDir(dir);
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    const hash = crypto.randomBytes(8).toString('hex');
    cb(null, `${file.fieldname}-${Date.now()}-${hash}${ext}`);
  },
});

const fileFilter = (req, file, cb) => {
  const allowed = [
    'image/jpeg', 'image/png', 'image/webp', 'image/jpg',
    'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/x-m4a', 'audio/mp4',
  ];
  if (allowed.includes(file.mimetype)) cb(null, true);
  else cb(new Error('Tipe file tidak didukung.'));
};

export const upload = multer({
  storage,
  fileFilter,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
});

export async function compressImage(filePath) {
  try {
    const ext = path.extname(filePath).toLowerCase();
    if (!['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) return filePath;

    const newPath = filePath.replace(/\.(jpe?g|png|webp)$/i, '.jpg');
    const image = await Jimp.read(filePath);
    if (image.width > 1080) {
      image.resize({ w: 1080 });
    }
    await image.write(newPath + '.tmp');
    fs.renameSync(newPath + '.tmp', newPath);
    if (newPath !== filePath) {
      try { fs.unlinkSync(filePath); } catch {}
    }
    return newPath;
  } catch (err) {
    console.error('Compress error:', err.message);
    return filePath;
  }
}

export function publicUrl(absPath) {
  if (!absPath) return null;
  const idx = absPath.indexOf('/public/');
  if (idx === -1) return absPath;
  return absPath.slice(idx + '/public'.length);
}

export function deleteIfExists(relUrl) {
  if (!relUrl) return;
  const abs = path.join(path.resolve('public'), relUrl.replace(/^\//, ''));
  if (fs.existsSync(abs)) {
    try { fs.unlinkSync(abs); } catch {}
  }
}
