import type { Database } from 'bun:sqlite';
import { setDb } from '../db/locator';
import { WebhookManager } from '../services/webhook-manager';
import { GroupSyncService } from '../services/group-sync';
import { ResponseQueue } from '../services/response-queue';
import { RemindersService } from '../services/reminders';
import { MaintenanceService } from '../services/maintenance';

export async function startServices(_db: Database): Promise<void> {
  // Exponer la DB globalmente vía locator para servicios que lo usen.
  try { setDb(_db); } catch {}

  // Iniciar aseguramiento automático del webhook en background (reintentos con backoff)
  try {
    WebhookManager.startAutoEnsure();
  } catch (e) {
    console.error('⚠️ Failed to start webhook auto-ensure loop:', e);
  }

  // Initialize groups - critical for operation (no abortar si falla)
  try {
    await GroupSyncService.checkInitialGroups();
  } catch (e) {
    console.error('⚠️ Initial groups check failed (will rely on schedulers to recover):', e);
  }

  // Start groups scheduler (periodic sync of groups)
  try {
    GroupSyncService.startGroupsScheduler();
    console.log('✅ Group scheduler started');
  } catch (e) {
    console.error('⚠️ Failed to start Group scheduler:', e);
  }

  // Initial members sync (non-blocking if fails)
  try {
    await GroupSyncService.syncMembersForActiveGroups();
    GroupSyncService.startMembersScheduler();
    console.log('✅ Group members scheduler started');
  } catch (e) {
    console.error('⚠️ Failed to run initial members sync or start scheduler:', e);
  }

  // Start response queue worker (background)
  try {
    await ResponseQueue.process();
    console.log('✅ ResponseQueue worker started');
    // Start cleanup scheduler (daily retention)
    ResponseQueue.startCleanupScheduler();
    console.log('✅ ResponseQueue cleanup scheduler started');
    RemindersService.start();
    console.log('✅ RemindersService started');
  } catch (e) {
    console.error('❌ Failed to start ResponseQueue worker or cleanup scheduler:', e);
  }

  // Mantenimiento (cleanup de miembros inactivos)
  try {
    MaintenanceService.start();
    console.log('✅ MaintenanceService started');
    // Ejecutar reconciliación de alias una vez al arranque (one-shot)
    try {
      await MaintenanceService.reconcileAliasUsersOnce();
      console.log('✅ MaintenanceService: reconciliación de alias ejecutada (one-shot)');
    } catch (e2) {
      console.error('⚠️ Failed to run alias reconciliation one-shot:', e2);
    }
  } catch (e) {
    console.error('⚠️ Failed to start MaintenanceService:', e);
  }
}

