'use strict';

async function runPostListenStartupTasks({ ensureMetasTable, ensureBillingSchema, ensureArkhonCardSchema, logger }) {
  for (const [name, task] of [
    ['metas', ensureMetasTable],
    ['billing', ensureBillingSchema],
    ['arkhon-card', ensureArkhonCardSchema],
  ]) {
    try {
      await task();
    } catch (error) {
      logger.warn({ event: 'startup_migration_deferred', name, message: error.message });
    }
  }
}

async function startServer(options) {
  const {
    server,
    io,
    port,
    publicDomain,
    logger,
    liveNotifications,
    socketService,
    updateRecovery,
    startupTasks,
  } = options;
  try {
    liveNotifications.init(io);
    socketService.init(io);
    server.listen(port, () => {
      const authMode = (!process.env.JWT_SECRET && !process.env.LOCAL_API_KEY) ? 'Sin auth (modo dev)' : 'Auth activa';
      const packageInfo = require('../../package.json');
      logger.info(`ARKHON Monitor v${packageInfo.version} - iniciado`);
      logger.info(`Servidor en http://localhost:${port}`);
      logger.info(authMode);
      logger.info('WebSocket activo - polling cada 5s');
      if (publicDomain) logger.info(`Dominio publico: https://${publicDomain}`);
      updateRecovery.schedulePendingValidation(logger);
      runPostListenStartupTasks({ ...startupTasks, logger }).catch((error) => {
        logger.warn({ event: 'startup_tasks_deferred', message: error.message });
      });
    });
  } catch (error) {
    logger.error('Error de inicializacion', { message: error.message, stack: error.stack });
    process.exit(1);
  }
}

module.exports = { runPostListenStartupTasks, startServer };
