// server/services/SyncManager.js
class SyncManager {
  constructor() {
    this.syncConfig = {
      resps: {
        model: 'User',
        method: 'getusersRespList',
        trackChanges: true,
        params: ['idapp'] // parametri necessari
      },
      workers: {
        model: 'User',
        method: 'getusersWorkersList',
        trackChanges: true,
        params: ['idapp']
      },
      groups: {
        model: 'Group',
        method: 'findAllIdApp',
        trackChanges: true,
        params: ['idapp']
      },
      mygroups: {
        model: 'MyGroup',
        method: 'findAllGroups',
        trackChanges: true,
        params: ['idapp']
      },
      products: {
        model: 'Product',
        method: 'findAllIdApp',
        trackChanges: true,
        params: ['idapp']
      },
      cart: {
        model: 'Cart',
        method: 'getCartByUserId',
        trackChanges: true,
        params: ['userId', 'idapp'],
        requiresAuth: true
      },
      orderscart: {
        model: 'OrdersCart',
        method: 'getOrdersCartByUserId',
        trackChanges: true,
        params: ['userId', 'idapp'],
        requiresAuth: true
      }
    };
  }

  async sync(syncRequest, idapp, user) {
    const results = {};
    const timestamp = Date.now();

    for (const [tableName, params] of Object.entries(syncRequest)) {
      const config = this.syncConfig[tableName];
      
      if (!config) {
        console.warn(`Tabella ${tableName} non configurata`);
        continue;
      }

      // Controlla autenticazione
      if (config.requiresAuth && !user) {
        results[tableName] = {
          data: null,
          timestamp: timestamp,
          fullSync: true
        };
        continue;
      }

      try {
        const data = await this.fetchTableData(
          tableName,
          config,
          params.lastSync,
          idapp,
          user
        );

        results[tableName] = {
          data: data,
          timestamp: timestamp,
          fullSync: params.lastSync === 0 || !config.trackChanges
        };
      } catch (error) {
        console.error(`Errore sync ${tableName}:`, error);
        results[tableName] = {
          error: error.message,
          timestamp: timestamp
        };
      }
    }

    return results;
  }

  async fetchTableData(tableName, config, lastSync, idapp, user) {
    const ModelClass = require(`../models/${config.model}`);
    
    // Prepara parametri
    const args = config.params.map(param => {
      if (param === 'idapp') return idapp;
      if (param === 'userId') return user?._id.toString() || '0';
      return null;
    });

    // Prima sync o no trackChanges: tutti i dati
    if (!config.trackChanges || lastSync === 0) {
      return await ModelClass[config.method](...args);
    }

    // Sync incrementale
    const query = {
      idapp: idapp,
      updatedAt: { $gt: new Date(parseInt(lastSync)) }
    };

    return await ModelClass.find(query).lean();
  }
}

module.exports = new SyncManager();