const express = require('express');
const multer = require('multer');
const { audit } = require('../db');
const { requireCapability } = require('../middleware/auth');
const { upsertImportedAssets } = require('../services/assets');
const { assetExport, extensionForUpload, rowsFromImport } = require('../services/importExport');

const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 16 * 1024 * 1024 } });
const router = express.Router();

router.get('/export/assets', async (req, res) => {
  const format = String(req.query.format || 'json').toLowerCase();
  const output = await assetExport(format, req.companyId);
  res.setHeader('Content-Type', output.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="${output.filename}"`);
  return res.send(output.body);
});

router.post('/import/assets', requireCapability('assets.bulk'), upload.single('file'), async (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'File is required' });
  const rows = await rowsFromImport(extensionForUpload(req.file.originalname), req.file.buffer);
  const imported = upsertImportedAssets(rows, req.user.id, req.companyId);
  audit(req.user.id, 'import', 'asset', null, null, { file: req.file.originalname, imported });
  res.json({ imported });
});

module.exports = router;
