const express = require('express');
const multer = require('multer');
const path = require('path');
const settingsController = require('../controllers/settings.controller');
const { requireAuth } = require('../middleware/auth');

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, path.join(__dirname, '..', '..', 'public', 'uploads'));
  },
  filename(req, file, cb) {
    const safe = `${Date.now()}-${file.fieldname}${path.extname(file.originalname).toLowerCase()}`;
    cb(null, safe);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 2 * 1024 * 1024 },
  fileFilter(req, file, cb) {
    if (!['image/png', 'image/jpeg', 'image/webp'].includes(file.mimetype)) return cb(new Error('Only PNG, JPG and WebP files are allowed.'));
    return cb(null, true);
  }
});

const router = express.Router();
router.get('/', requireAuth, settingsController.index);
router.post('/', requireAuth, upload.fields([{ name: 'logo', maxCount: 1 }, { name: 'signature', maxCount: 1 }, { name: 'seal', maxCount: 1 }]), settingsController.update);
module.exports = router;
