'use strict';

const { handleImportPreview } = require('./catalogPreview');
const { handleBulkApply } = require('./catalogApply');
const { handlerNotImplemented } = require('../../agent/commandHandlers/schemas');
const { handleInventoryTransfer } = require('./catalogTransfer');

async function handleInventorySnapshot(command, config = {}, deps = {}) {
  const payload = command.payload || {};
  const branchId = config.syncContext?.branch_id || config.syncContext?.branchId;
  if (payload.branch_id && branchId && payload.branch_id !== branchId) {
    throw Object.assign(new Error('branch_id no coincide con el agente local'), { code: 'scope_mismatch' });
  }
  const pool = deps.pool || await require('../../db').getPool();
  const extractor = require('../../agent/mssqlExtractors/inventarioExtractor');
  const limit = Math.min(Math.max(Number(payload.options?.limit || 1000), 1), 5000);
  const rows = await extractor.extract(pool, null, limit);
  return {
    snapshot_id: payload.snapshot_id || null,
    branch_id: payload.branch_id || branchId || null,
    count: rows.length,
    items: rows.map((row) => row.payload || row),
  };
}

const HANDLERS = {
  'catalog.import.preview': handleImportPreview,
  'catalog.import.apply': handleBulkApply,
  'catalog.bulk_apply': handleBulkApply,
  'inventory.snapshot.request': handleInventorySnapshot,
  'inventory.transfer.execute': handleInventoryTransfer,
  'catalog.product.upsert': (command) => handlerNotImplemented(command.command_type, 'Producto central requiere mapper SoftRestaurant transaccional.'),
  'catalog.product.disable': (command) => handlerNotImplemented(command.command_type, 'Desactivar producto requiere mapper SoftRestaurant transaccional.'),
  'catalog.price.update': (command) => handlerNotImplemented(command.command_type, 'Usar CHANGE_PRODUCT_PRICE hasta cerrar mapper centralizador.'),
  'catalog.user.upsert': (command) => handlerNotImplemented(command.command_type, 'Usuarios POS requieren tratamiento seguro de PIN/password.'),
  'catalog.waiter.upsert': (command) => handlerNotImplemented(command.command_type, 'Meseros requieren tratamiento seguro de PIN/password.'),
  'catalog.recipe.upsert': (command) => handlerNotImplemented(command.command_type, 'Recetas requieren mapper SoftRestaurant transaccional.'),
  'catalog.inventory.item.upsert': (command) => handlerNotImplemented(command.command_type, 'Inventario central requiere mapper SoftRestaurant transaccional.'),
  'catalog.payment_method.upsert': (command) => handlerNotImplemented(command.command_type, 'Formas de pago requieren mapper SoftRestaurant transaccional.'),
  'catalog.supplier.upsert': (command) => handlerNotImplemented(command.command_type, 'Proveedores requieren mapper SoftRestaurant transaccional.'),
};

module.exports = {
  HANDLERS,
  handleImportPreview,
  handleInventorySnapshot,
};
