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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const { rateLimit, ipKeyGenerator } = require('express-rate-limit');
require('dotenv').config();
const validateEnv = require('./config/validateEnv');
validateEnv();

const authRoutes = require('./routes/auth');
const doctorRoutes = require('./routes/doctors');
const patientRoutes = require('./routes/patients');
const appointmentRoutes = require('./routes/appointments');
const adminRoutes = require('./routes/admin');
const notificationRoutes = require('./routes/notifications');
const virtualCheckinRoutes = require('./routes/virtualCheckin'); // Issue #39
const analyticsRoutes = require('./routes/analytics'); // Issue #44
const walkinRoutes = require('./routes/walkin'); // Issue #42
const multiDoctorRoutes = require('./routes/multiDoctor');
const feedbackRoutes = require('./routes/feedback');
const insuranceRoutes = require('./routes/insurance');
const paymentRoutes = require('./routes/payments');
const messageRoutes = require('./routes/messages');
const exportRoutes = require('./routes/export');
const symptomCheckerRoutes = require('./routes/symptomChecker');
const departmentRoutes = require('./routes/departments');
const prescriptionRoutes = require('./routes/prescriptions');
const errorHandler = require('./middleware/errorHandler');
const { initCronJobs } = require('./jobs/reminderJobs');
const logger = require('./config/logger');
const requestLogger = require('./middleware/requestLogger');

const app = express();

// Parse JSON for all routes EXCEPT the Stripe webhook (which needs the raw body for signature verification)
app.use((req, res, next) => {
    if (req.originalUrl === '/api/payments/webhook') {
        return next();
    }
    express.json({ limit: '1mb' })(req, res, next);
});

// Structured request logging middleware (Morgan + Winston)
app.use(requestLogger);

// Root Route (Moved to top for visibility)
app.get('/', (req, res) => {
    res.json({ status: 'ok', message: 'Hospital Management API is running', version: '1.0.1' });
});

// Issue #92: Swagger API Documentation
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');

const swaggerOptions = {
    definition: {
        openapi: '3.0.0',
        info: {
            title: 'Hospital Management API',
            version: '1.0.0',
            description: 'API documentation for the Patient Appointment Scheduling System',
        },
        servers: [
            {
                url: process.env.APP_URL || 'http://localhost:7860',
            },
        ],
        components: {
            securitySchemes: {
                bearerAuth: {
                    type: 'http',
                    scheme: 'bearer',
                    bearerFormat: 'JWT'
                }
            }
        },
        security: [
            {
                bearerAuth: []
            }
        ]
    },
    apis: ['./src/routes/*.js', './src/server.js'],
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);
if (process.env.NODE_ENV !== 'production') {
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}

// Security Middleware β€” baseline Helmet (CSP configured after origins are resolved below)
app.use(helmet({
    crossOriginResourcePolicy: { policy: 'cross-origin' },
    contentSecurityPolicy: false,   // set via a dedicated middleware below once origins are known
}));

// Response compression (gzip/brotli) β€” reduces payload 2–5Γ— for JSON-heavy API responses
app.use(compression());

// Strict CORS
function normalizeOrigin(value) {
    if (!value) return null;

    const trimmed = value.trim();
    if (!trimmed) return null;

    try {
        return new URL(trimmed).origin;
    } catch {
        return trimmed;
    }
}

const whitelist = new Set([
    ...(process.env.CORS_ALLOWED_ORIGINS ? process.env.CORS_ALLOWED_ORIGINS.split(',') : []),
    ...(process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : []),
    process.env.APP_URL,
    process.env.FRONTEND_URL,
    ...(process.env.NODE_ENV !== 'production' ? ['http://localhost:5173', 'http://127.0.0.1:5173'] : [])
].map(normalizeOrigin).filter(Boolean));

// [SEC-008] CORS: whitelist-only in production; localhost pass-through in development.
// Add specific deployment URLs to ALLOWED_ORIGINS env var β€” never use platform-wide wildcards.
const corsOptions = {
    origin: function (origin, callback) {
        // Allow requests with no origin (mobile apps, curl, Postman, server-to-server)
        if (!origin) return callback(null, true);

        const normalizedOrigin = normalizeOrigin(origin);

        // 1. Allow explicitly whitelisted origins (from env var or APP_URL/FRONTEND_URL)
        if (whitelist.has(normalizedOrigin)) return callback(null, true);

        // 2. In development, allow any localhost / 127.0.0.1 variant
        if (process.env.NODE_ENV !== 'production') {
            if (
                /^https?:\/\/localhost:\d+$/.test(origin) ||
                /^https?:\/\/127\.0\.0\.1:\d+$/.test(origin)
            ) {
                return callback(null, true);
            }
        }

        callback(new Error('Not allowed by CORS'));
    },
    credentials: true
};
app.use(cors(corsOptions));

// ── Content Security Policy ───────────────────────────────────────────────────
// Applied AFTER the CORS whitelist is built so connect-src stays in sync with the
// allowed origins. The API serves JSON to the SPA; scripts/styles are loaded by
// the frontend bundle, not here, so directives are intentionally restrictive.
app.use(helmet.contentSecurityPolicy({
    useDefaults: true,
    directives: {
        defaultSrc: ["'self'"],
        // The SPA connects to this API plus any whitelisted deployment origins
        connectSrc: ["'self'", ...whitelist],
        imgSrc: ["'self'", 'data:', 'blob:'],
        fontSrc: ["'self'", 'data:'],
        objectSrc: ["'none'"],
        frameAncestors: ["'none'"],
        baseUri: ["'self'"],
        formAction: ["'self'"],
    },
}));

// ── Global Rate Limiter ────────────────────────────────────────────────────────
// Reads window/max from env so production can be tuned without code changes.
// standardHeaders: true  β†’ emits RateLimit-Limit / RateLimit-Remaining / Retry-After (RFC 6585)
// legacyHeaders: false   β†’ suppresses X-RateLimit-* to keep responses uncluttered
const rateLimitWindowMins = parseInt(process.env.RATE_LIMIT_WINDOW_MINS, 10) || 15;
const rateLimitMax = parseInt(process.env.RATE_LIMIT_MAX, 10) || 100;

const globalLimiter = rateLimit({
    windowMs: rateLimitWindowMins * 60 * 1000,
    max: rateLimitMax,
    standardHeaders: true,
    legacyHeaders: false,
    handler: (req, res) => {
        res.status(429).json({
            status: 'fail',
            code: 'TOO_MANY_REQUESTS',
            message: `Too many requests from this IP β€” please try again after ${rateLimitWindowMins} minutes.`,
        });
    },
});

// ── Auth Rate Limiter (Brute-force Protection) ─────────────────────────────────
// Tighter window specifically for login / register to resist credential stuffing.
// 10 attempts per hour per IP β€” legitimate users will never hit this.
//
// keyGenerator includes req.path so /login and /register maintain independent
// counters per IP. Without this, exhausting the /login budget would immediately
// block /register attempts from the same IP (and vice-versa).
const authLimiter = rateLimit({
    windowMs: 60 * 60 * 1000, // 1 hour
    max: 10,
    standardHeaders: true,
    legacyHeaders: false,
    keyGenerator: (req) => `${ipKeyGenerator(req.ip)}::${req.path}`,
    handler: (req, res) => {
        res.status(429).json({
            status: 'fail',
            code: 'TOO_MANY_REQUESTS',
            message: 'Too many authentication attempts β€” please try again after 1 hour.',
        });
    },
});

if (process.env.DISABLE_RATE_LIMITER !== 'true') {
    app.use('/api/', globalLimiter);
    app.use('/api/auth/login', authLimiter);
    app.use('/api/auth/register', authLimiter);
    app.use('/api/auth/forgot-password', authLimiter);
}

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/doctors', doctorRoutes);
app.use('/api/patients', patientRoutes);
app.use('/api/appointments', appointmentRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/virtual-checkin', virtualCheckinRoutes); // Issue #39
app.use('/api/analytics', analyticsRoutes); // Issue #44
app.use('/api/walkin', walkinRoutes); // Issue #42
app.use('/api/multi-doctor', multiDoctorRoutes);
app.use('/api/feedback', feedbackRoutes);
app.use('/api/insurance', insuranceRoutes);
app.use('/api/payments', paymentRoutes);
app.use('/api/messages', messageRoutes);
app.use('/api/export', exportRoutes);
app.use('/api/symptom-checker', symptomCheckerRoutes);
app.use('/api/departments', departmentRoutes);
app.use('/api/prescriptions', prescriptionRoutes);

// ============================================================================
// Monitoring & Health Probes (Issue #122 / Day 14)
// ============================================================================

const net = require('net');

/**
 * Helper to check Redis connection via a TCP socket probe.
 * Returns a promise resolving to the health status of Redis.
 */
async function checkRedisHealth() {
    const host = process.env.REDIS_HOST;
    const port = parseInt(process.env.REDIS_PORT, 10) || 6379;
    const url = process.env.REDIS_URL;

    // If no Redis connection parameters are configured, it is considered disabled (healthy fallback)
    if (!host && !url) {
        return { healthy: true, status: 'disabled', message: 'Redis is not configured' };
    }

    let targetHost = host || 'localhost';
    let targetPort = port;

    if (url) {
        try {
            const parsed = new URL(url);
            targetHost = parsed.hostname;
            targetPort = parseInt(parsed.port, 10) || 6379;
        } catch (e) {
            return { healthy: false, status: 'error', error: 'Invalid REDIS_URL format: ' + e.message };
        }
    }

    return new Promise((resolve) => {
        const socket = new net.Socket();
        socket.setTimeout(2000); // 2 second timeout for connection probe

        socket.on('connect', () => {
            socket.destroy();
            resolve({ healthy: true, status: 'connected' });
        });

        socket.on('error', (err) => {
            socket.destroy();
            resolve({ healthy: false, status: 'error', error: err.message });
        });

        socket.on('timeout', () => {
            socket.destroy();
            resolve({ healthy: false, status: 'timeout', error: 'Connection timed out (2000ms)' });
        });

        socket.connect(targetPort, targetHost);
    });
}

/**
 * @swagger
 * /api/health:
 *   get:
 *     summary: Retrieve detailed system health and performance telemetry
 *     description: Exposes system uptime, database status, cron scheduler metadata, and process performance statistics (CPU/Memory).
 *     tags: [Monitoring]
 *     responses:
 *       200:
 *         description: Telemetry successfully retrieved
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 */
app.get('/api/health', async (req, res) => {
    let dbStatus = { healthy: false, error: null };
    let dbStats = null;

    try {
        const db = require('./config/db');
        // Simple query check
        await db.query('SELECT 1');
        dbStatus.healthy = true;
        
        if (typeof db.getPoolStats === 'function') {
            dbStats = db.getPoolStats();
        }
    } catch (err) {
        dbStatus.error = err.message;
    }

    const { getCronStatus } = require('./jobs/reminderJobs');
    const schedulerStatus = typeof getCronStatus === 'function' ? getCronStatus() : null;

    // Collect process and system performance telemetry
    const memUsage = process.memoryUsage();
    const performanceStats = {
        memory: {
            rssMb: Math.round((memUsage.rss / 1024 / 1024) * 100) / 100,
            heapTotalMb: Math.round((memUsage.heapTotal / 1024 / 1024) * 100) / 100,
            heapUsedMb: Math.round((memUsage.heapUsed / 1024 / 1024) * 100) / 100,
            externalMb: Math.round((memUsage.external / 1024 / 1024) * 100) / 100
        },
        cpu: process.cpuUsage(),
        nodeVersion: process.version
    };

    const sseManager = require('./services/sseManager');
    const sseConnectionsCount = typeof sseManager.getActiveConnectionsCount === 'function'
        ? sseManager.getActiveConnectionsCount()
        : 0;

    res.json({
        status: dbStatus.healthy ? 'ok' : 'error',
        message: 'Hospital API is running',
        uptime: process.uptime(),
        sseConnections: sseConnectionsCount,
        database: {
            healthy: dbStatus.healthy,
            error: dbStatus.error,
            stats: dbStats
        },
        scheduler: schedulerStatus,
        performance: performanceStats
    });
});

/**
 * @swagger
 * /healthz:
 *   get:
 *     summary: Simple health probe for container orchestrators and load balancers
 *     description: Checks MySQL database and Redis connection health. Returns HTTP 200 if both connections are healthy, and HTTP 503 if any required service is down.
 *     tags: [Monitoring]
 *     responses:
 *       200:
 *         description: Both MySQL database and Redis connections are healthy
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *       503:
 *         description: One or more critical connections are unhealthy
 */
app.get(['/healthz', '/api/healthz'], async (req, res) => {
    let dbHealthy = false;
    let dbError = null;

    try {
        const db = require('./config/db');
        await db.query('SELECT 1');
        dbHealthy = true;
    } catch (err) {
        dbError = err.message;
    }

    const redisStatus = await checkRedisHealth();
    const overallHealthy = dbHealthy && redisStatus.healthy;

    const responsePayload = {
        status: overallHealthy ? 'ok' : 'error',
        timestamp: new Date().toISOString(),
        database: {
            healthy: dbHealthy,
            error: dbError
        },
        redis: redisStatus
    };

    if (overallHealthy) {
        res.status(200).json(responsePayload);
    } else {
        res.status(503).json(responsePayload);
    }
});



// ============================================================================
// Metrics Endpoints β€” gated behind ADMIN auth (PR #13)
// ============================================================================
const { authenticate, requireRole } = require('./middleware/authenticate');
const metricsService = require('./services/metricsService');

/**
 * @swagger
 * /api/metrics:
 *   get:
 *     summary: JSON latency percentile snapshot (ADMIN only)
 *     description: Returns p50/p95/p99 response time percentiles per route, total request counts, and process uptime. Requires ADMIN role.
 *     tags: [Monitoring]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: Metrics snapshot
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden β€” requires ADMIN role
 */
app.get('/api/metrics', authenticate, requireRole(['ADMIN']), (req, res) => {
    res.json(metricsService.getSnapshot());
});

/**
 * @swagger
 * /api/metrics/prometheus:
 *   get:
 *     summary: Prometheus text-format metrics (ADMIN only)
 *     description: Returns metrics in Prometheus exposition format for scraping by Grafana / Prometheus. Requires ADMIN role.
 *     tags: [Monitoring]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: Prometheus-formatted metrics
 *         content:
 *           text/plain:
 *             schema:
 *               type: string
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden β€” requires ADMIN role
 */
app.get('/api/metrics/prometheus', authenticate, requireRole(['ADMIN']), (req, res) => {
    res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
    res.send(metricsService.toPrometheusFormat());
});

// Global Error Handler (Must be last)
app.use(errorHandler);

const PORT = process.env.PORT || 7860;
if (process.env.NODE_ENV !== 'test') {
    const server = app.listen(PORT, () => {
        logger.info(`Server listening on port ${PORT} in ${process.env.NODE_ENV || 'development'} mode`);
        // Initialize Background Jobs
        initCronJobs();

        // Run database migrations programmatically on startup (forked child process)
        try {
            const { fork } = require('child_process');
            const path = require('path');
            const migrationProcess = fork(path.join(__dirname, '../database/apply_migrations.js'));
            migrationProcess.on('exit', (code) => {
                if (code === 0) {
                    logger.info('Database migrations verified and applied successfully.');
                } else {
                    logger.error(`Database migrations failed to execute (exit code: ${code}).`);
                }
            });
        } catch (migError) {
            logger.error('Failed to initiate migrations child process:', migError);
        }
    });

    // ── Graceful Shutdown ──────────────────────────────────────────────────────
    // On SIGTERM (container orchestrators) / SIGINT (Ctrl-C), stop accepting new
    // connections, drain the MySQL pool, and exit cleanly so in-flight requests
    // are not dropped on deploys / restarts.
    let shuttingDown = false;
    async function shutdown(signal) {
        if (shuttingDown) return;
        shuttingDown = true;
        logger.info(`Received ${signal} β€” shutting down gracefully`);

        // Force-exit if cleanup takes longer than the timeout
        const forceExit = setTimeout(() => {
            logger.error('Graceful shutdown timed out β€” forcing exit');
            process.exit(1);
        }, 10000);
        forceExit.unref();

        server.close((err) => {
            if (err) logger.error('Error closing HTTP server:', err);

            try {
                const db = require('./config/db');
                db.end().then(() => {
                    logger.info('Database pool closed');
                    process.exit(err ? 1 : 0);
                }).catch((dbErr) => {
                    logger.error('Error closing database pool:', dbErr);
                    process.exit(1);
                });
            } catch {
                // DB module not loaded β€” exit once HTTP server is closed
                process.exit(err ? 1 : 0);
            }
        });
    }

    process.on('SIGTERM', () => shutdown('SIGTERM'));
    process.on('SIGINT', () => shutdown('SIGINT'));
}

module.exports = app;