const path = require("path");
const fs = require("fs");

const TRAINING_DIR = path.join(__dirname, "..", "uploads", "training");

const ALLOWED = new Set([
  "video/mp4",
  "video/webm",
  "video/quicktime",
  "video/x-msvideo",
]);

/**
 * Saves a training video file under uploads/training/.
 * @returns {Promise<string>} filename only (not full path)
 */
async function saveTrainingVideo(file) {
  if (!file) throw new Error("No video file");
  if (!ALLOWED.has(file.mimetype)) {
    throw new Error(`Invalid video type: ${file.mimetype}`);
  }
  if (!fs.existsSync(TRAINING_DIR)) {
    fs.mkdirSync(TRAINING_DIR, { recursive: true });
  }
  const safe = String(file.name || "video").replace(/[^a-zA-Z0-9._-]/g, "_");
  const fileName = `${Date.now()}-${safe}`;
  const dest = path.join(TRAINING_DIR, fileName);
  await file.mv(dest);
  return fileName;
}

function deleteTrainingVideoFile(fileName) {
  if (!fileName) return;
  const p = path.join(TRAINING_DIR, fileName);
  if (fs.existsSync(p)) fs.unlinkSync(p);
}

module.exports = { saveTrainingVideo, deleteTrainingVideoFile, TRAINING_DIR };
