import { Router } from 'express';
import multer from 'multer';
import * as factoryDefaultsController from '../controllers/factoryDefaults.controller.js';
import { authenticate, requirePermission } from '../middleware/auth.js';

const router = Router();

// In-Memory-Upload für die ZIP – wird direkt verarbeitet, keine temporäre Datei.
const upload = multer({
  storage: multer.memoryStorage(),
  fileFilter: (_req, file, cb) => {
    const ok =
      file.mimetype === 'application/zip' ||
      file.mimetype === 'application/x-zip-compressed' ||
      file.mimetype === 'application/octet-stream' || // manche Browser senden das für .zip
      file.originalname.toLowerCase().endsWith('.zip');
    if (ok) cb(null, true);
    else cb(new Error('Nur ZIP-Dateien sind erlaubt'));
  },
  limits: { fileSize: 50 * 1024 * 1024 },
});

// Preview (was wäre im Export drin?)
router.get(
  '/preview',
  authenticate,
  requirePermission('settings:read'),
  factoryDefaultsController.previewFactoryDefaults,
);

// Export als ZIP-Download
router.get(
  '/export',
  authenticate,
  requirePermission('settings:update'),
  factoryDefaultsController.exportFactoryDefaults,
);

// Import aus ZIP (multipart, Feld 'zip')
router.post(
  '/import',
  authenticate,
  requirePermission('settings:update'),
  upload.single('zip'),
  factoryDefaultsController.importFactoryDefaults,
);

export default router;
