// server/routes/sync.js
const express = require('express');
const router = express.Router();
const SyncManager = require('../services/SyncManager');
const { authenticate_noerror_WithUserLean } = require('../middleware/authenticate');

router.post('/sync/:idapp', authenticate_noerror_WithUserLean, async (req, res) => {
  try {
    const { idapp } = req.params;
    const { tables } = req.body; // { users: { lastSync: 0 }, groups: { lastSync: 123456 } }
    
    const results = await SyncManager.sync(tables, idapp, req.user);
    
    res.json({
      success: true,
      data: results,
      serverTime: Date.now()
    });
    
  } catch (error) {
    console.error('Sync error:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;