const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const AdmZip = require('adm-zip');
const { convertWithPoppler } = require('../utils/pdfToImages');

const router = express.Router();

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`)
});

const upload = multer({ storage });

router.post('/', upload.fields([{ name: 'pdf' }, { name: 'zip' }]), async (req, res) => {
  try {
    const pdfFile = req.files['pdf']?.[0];
    const zipFile = req.files['zip']?.[0];

    if (!pdfFile || !zipFile) {
      return res.status(400).json({ error: 'PDF and ZIP required' });
    }

    const pdfOriginalPath = path.join(__dirname, '../uploads/originals', pdfFile.filename);
    fs.renameSync(pdfFile.path, pdfOriginalPath);

    const mediaDir = path.join(__dirname, '../uploads/media');
    fs.mkdirSync(mediaDir, { recursive: true });

    const zip = new AdmZip(zipFile.path);
    zip.getEntries().forEach(entry => {
      if (!entry.isDirectory) {
        const fileName = path.basename(entry.entryName);
        const outputPath = path.join(mediaDir, fileName);
        fs.writeFileSync(outputPath, entry.getData());
      }
    });

    const slidesDir = path.join(__dirname, '../uploads/slides');
    const slideImages = await convertWithPoppler(pdfOriginalPath, slidesDir);

    const slidesWithMedia = slideImages.map(slide => {
      const { slideNumber, imageUrl } = slide;
      const audioFile = `slide${slideNumber}.mp3`;
      const videoFile = `slide${slideNumber}.mp4`;

      return {
        slideNumber,
        imageUrl: `/slides/${path.basename(imageUrl)}`,
        audioUrl: fs.existsSync(path.join(mediaDir, audioFile)) ? `/media/${audioFile}` : null,
        videoUrl: fs.existsSync(path.join(mediaDir, videoFile)) ? `/media/${videoFile}` : null,
      };
    });

    fs.unlinkSync(zipFile.path);
    return res.json({ slides: slidesWithMedia });
  } catch (err) {
    console.error('Upload error:', err);
    return res.status(500).json({ error: 'Upload failed' });
  }
});

module.exports = router;
