const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const settingsController = require('../controllers/settingController');

// Configure multer for file uploads
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = path.join(__dirname, '../uploads');
    // Create uploads directory if it doesn't exist
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // Generate unique filename: companyId_branchId_timestamp.extension
    const companyId = req.body.companyId || 'default';
    const branchId = req.body.branchId || 'default';
    const timestamp = Date.now();
    const ext = path.extname(file.originalname);
    const filename = `company_logo_${companyId}_${branchId}_${timestamp}${ext}`;
    cb(null, filename);
  }
});

const fileFilter = (req, file, cb) => {
  // Accept only image files
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed!'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  }
});

// Route to upload company logo
router.post('/upload-logo', upload.single('logo'), settingsController.uploadLogo);

// Route to create or update settings
router.post('/', settingsController.createOrUpdateSettings);

// Route to get settings (can filter by companyId and branchId)
router.get('/', settingsController.getSettings);

module.exports = router;
