const express = require('express');
const router = express.Router();
const pool = require('../db');
const authenticateToken = require('../middleware/auth');

// Ruta principală pentru sincronizare
router.post('/sync', async (req, res) => {
    try {
        const { deviceId, products, lastSync } = req.body;

        // 1. Salvare produse noi în baza de date
        await pool.promise().query(
            'INSERT INTO synced_products (product_id, product_data, device_id) VALUES ? ' +
            'ON DUPLICATE KEY UPDATE product_data = VALUES(product_data), last_modified = NOW()',
            [products.map(p => [p.id, JSON.stringify(p), deviceId])]
        );

        // 2. Obține toate produsele actualizate după ultima sincronizare
        const [results] = await pool.promise().query(
            `SELECT product_data FROM synced_products 
             WHERE last_modified > ? OR device_id = ?`,
            [new Date(lastSync), deviceId]
        );

        const allProducts = results.map(r => JSON.parse(r.product_data));

        res.json({
            status: 'success',
            products: allProducts,
            newLastSync: new Date().toISOString()
        });

    } catch (err) {
        console.error('Eroare sincronizare:', err);
        res.status(500).json({ error: 'Eroare server' });
    }
});

// Ruta pentru ștergere
router.post('/delete', async (req, res) => {
    try {
        const { productIds } = req.body;
        await pool.promise().query(
            'DELETE FROM synced_products WHERE product_id IN (?)',
            [productIds]
        );
        res.json({ status: 'success' });
    } catch (err) {
        console.error('Eroare ștergere:', err);
        res.status(500).json({ error: 'Eroare server' });
    }
});

module.exports = router;