// routes/editorSave.js
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const router = express.Router();

const SLIDES_DIR = path.join(__dirname, '../uploads/slides');
const MEDIA_DIR = path.join(__dirname, '../uploads/media');

// Ensure folders exist
if (!fs.existsSync(SLIDES_DIR)) fs.mkdirSync(SLIDES_DIR, { recursive: true });
if (!fs.existsSync(MEDIA_DIR)) fs.mkdirSync(MEDIA_DIR, { recursive: true });

// Multer memory storage to process in route handler
const storage = multer.memoryStorage();
const upload = multer({ storage });

// Truncate directories before saving new files
const clearDirectories = () => {
  fs.readdirSync(SLIDES_DIR).forEach(f => fs.unlinkSync(path.join(SLIDES_DIR, f)));
  fs.readdirSync(MEDIA_DIR).forEach(f => fs.unlinkSync(path.join(MEDIA_DIR, f)));
};

router.post('/editor/save', upload.fields([
  { name: 'slide' },
  { name: 'audio' },
  { name: 'video' }
]), async (req, res) => {
  try {
    clearDirectories();

    const { slideNumbers } = req.body; // e.g., "1,2,3"
    const slideOrder = Array.isArray(slideNumbers) ? slideNumbers : slideNumbers.split(',');

    const slides = req.files['slide'] || [];
    const audios = req.files['audio'] || [];
    const videos = req.files['video'] || [];

    const fileMap = (filesArray) => {
      const map = {};
      filesArray.forEach(file => {
        const match = file.originalname.match(/slide(\d+)(_quiz)?\.(jpg|jpeg|png|mp3|mp4)/);
        if (match) {
          const index = match[1];
          const isQuiz = !!match[2];
          const ext = match[3];
          map[index] = { file, isQuiz, ext };
        }
      });
      return map;
    };

    const slideMap = fileMap(slides);
    const audioMap = fileMap(audios);
    const videoMap = fileMap(videos);

    slideOrder.forEach((originalIndex, idx) => {
      const newIndex = (idx + 1).toString();

      // Slide image
      if (slideMap[originalIndex]) {
        const { file, isQuiz, ext } = slideMap[originalIndex];
        const newName = `slide${newIndex}${isQuiz ? '_quiz' : ''}.${ext}`;
        fs.writeFileSync(path.join(SLIDES_DIR, newName), file.buffer);
      }

      // Audio file
      if (audioMap[originalIndex]) {
        const { file } = audioMap[originalIndex];
        fs.writeFileSync(path.join(MEDIA_DIR, `slide${newIndex}.mp3`), file.buffer);
      }

      // Video file
      if (videoMap[originalIndex]) {
        const { file } = videoMap[originalIndex];
        fs.writeFileSync(path.join(MEDIA_DIR, `slide${newIndex}.mp4`), file.buffer);
      }
    });

    return res.json({ success: true });
  } catch (err) {
    console.error('Save error:', err);
    res.status(500).json({ error: 'Failed to save slides/media' });
  }
});

module.exports = router;
