'use strict';

const { previewCatalogs } = require('./softrestaurant.extractors');

async function handleImportPreview(command, config = {}, deps = {}) {
  const payload = command.payload || {};
  const tenantId = config.syncContext?.tenant_id || config.syncContext?.tenantId;
  const branchId = config.syncContext?.branch_id || config.syncContext?.branchId;
  if (payload.tenant_id && tenantId && payload.tenant_id !== tenantId) {
    throw Object.assign(new Error('tenant_id no coincide con el agente local'), { code: 'scope_mismatch' });
  }
  if (payload.source_branch_id && branchId && payload.source_branch_id !== branchId) {
    throw Object.assign(new Error('source_branch_id no coincide con el agente local'), { code: 'scope_mismatch' });
  }
  const limit = Math.min(Math.max(Number(payload.options?.limit || 200), 1), 1000);
  const catalogs = await (deps.previewCatalogs || previewCatalogs)({
    catalogTypes: payload.catalog_types || [],
    limit,
    pool: deps.pool || null,
  });
  return {
    import_job_id: payload.import_job_id,
    source_branch_id: payload.source_branch_id,
    catalogs,
  };
}

module.exports = { handleImportPreview };
