import './env.js';

// Prevent unhandled rejections from crashing the process
process.on('unhandledRejection', (err) => {
  console.error('[UNHANDLED REJECTION]', err);
});
process.on('uncaughtException', (err) => {
  console.error('[UNCAUGHT EXCEPTION]', err);
});

import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { serve } from '@hono/node-server';

import { authMiddleware } from './middleware/auth';
import { auditMiddleware } from './middleware/audit';

import { pipelinesRouter } from './routes/pipelines';
import { tasksRouter } from './routes/tasks';
import { approvalsRouter } from './routes/approvals';
import { agentsRouter } from './routes/agents';
import { assetsRouter } from './routes/assets';
import { notificationsRouter } from './routes/notifications';
import { auditRouter } from './routes/audit';
import { webhooksRouter } from './routes/webhooks';
import { feedbackRouter } from './routes/feedback';

import { initWebSocketBroadcaster, getConnectedClients } from './ws/server';
import { startNotificationWorker } from './events/consumers/notification-worker';
import { startAuditWriter } from './events/consumers/audit-writer';

// ═══════════════════════════════════════════════════════════
// GooseFactory API Server
// ═══════════════════════════════════════════════════════════

const app = new Hono();

// ─── Global Middleware ──────────────────────────────────
app.use('*', cors({
  origin: process.env.CORS_ORIGIN || '*',
  allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
  maxAge: 86400,
}));
app.use('*', logger());

// ─── Health Check (no auth) ────────────────────────────
app.get('/health', (c) => {
  return c.json({
    status: 'ok',
    service: 'goosefactory-api',
    version: '0.1.0',
    timestamp: new Date().toISOString(),
    wsClients: getConnectedClients(),
  });
});

// ─── API Info (no auth) ────────────────────────────────
app.get('/', (c) => {
  return c.json({
    name: 'GooseFactory API',
    version: 'v1',
    docs: '/v1',
    health: '/health',
  });
});

// ─── v1 API Routes (authenticated) ─────────────────────
const v1 = new Hono();

// Auth + audit on all v1 routes
v1.use('*', authMiddleware);
v1.use('*', auditMiddleware);

// Mount route modules
v1.route('/pipelines', pipelinesRouter);
v1.route('/tasks', tasksRouter);
v1.route('/approvals', approvalsRouter);
v1.route('/agents', agentsRouter);
v1.route('/assets', assetsRouter);
v1.route('/notifications', notificationsRouter);
v1.route('/audit', auditRouter);
v1.route('/webhooks', webhooksRouter);
v1.route('/feedback', feedbackRouter);

// Dashboard summary endpoint
v1.get('/dashboard/summary', async (c) => {
  // This aggregates data from multiple services
  // TODO: Move to a dashboard service
  return c.json({
    success: true,
    data: {
      activePipelines: 0,
      pendingTasks: 0,
      slaBreaches: 0,
      agentsOnline: 0,
      wsClients: getConnectedClients(),
      timestamp: new Date().toISOString(),
    },
  });
});

app.route('/v1', v1);

// ─── 404 Handler ───────────────────────────────────────
app.notFound((c) => {
  return c.json(
    { success: false, error: { code: 'NOT_FOUND', message: `Route not found: ${c.req.method} ${c.req.url}` } },
    404
  );
});

// ─── Error Handler ─────────────────────────────────────
app.onError((err, c) => {
  console.error('[API Error]', err);
  return c.json(
    { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
    500
  );
});

// ═══════════════════════════════════════════════════════════
// Start Server
// ═══════════════════════════════════════════════════════════

const PORT = parseInt(process.env.PORT || '4000', 10);

// Initialize event consumers
initWebSocketBroadcaster();
startNotificationWorker();
// startAuditWriter(); // Enable when DB is connected

// SLA monitor - enable in production
// import { startSLAMonitorConsumer } from './events/consumers/sla-monitor';
// startSLAMonitorConsumer();

console.log(`
╔═══════════════════════════════════════════════════╗
║         🏭 GooseFactory API v0.1.0               ║
║                                                   ║
║  REST API:   http://localhost:${PORT}/v1            ║
║  Health:     http://localhost:${PORT}/health         ║
║  WebSocket:  ws://localhost:${PORT}/v1/ws            ║
║                                                   ║
║  Mode: ${process.env.DEV_MODE === 'true' ? 'DEVELOPMENT (auth bypassed)' : 'PRODUCTION              '}  ║
╚═══════════════════════════════════════════════════╝
`);

serve({
  fetch: app.fetch,
  port: PORT,
});

export default app;
export type AppType = typeof app;
