import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import NotificationSseService from '#services/notification/notificationSseService';
import Config from '#config';

export default (_express: Application) => {
	const sseService = NotificationSseService.getInstance();
	return <Resource>{
		get: {
			middleware: [verify],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;

					// C-05: Validate origin against FRONTEND_URL whitelist - no wildcard fallback
					const allowedOrigins = (Config.server.frontendUrl || '')
						.split(',')
						.map((o) => o.trim())
						.filter(Boolean);

					if (allowedOrigins.length === 0) {
						console.error('SSE connection rejected: FRONTEND_URL not configured');
						return res.status(500).json({
							success: false,
							error: { code: 'CONFIG_ERROR', message: 'SSE not configured: FRONTEND_URL required' },
						});
					}

					const requestOrigin = req.headers.origin || '';
					if (!allowedOrigins.includes(requestOrigin)) {
						console.error(`SSE connection rejected: origin ${requestOrigin} not in whitelist`);
						return res.status(403).json({
							success: false,
							error: { code: 'FORBIDDEN', message: 'Origin not allowed' },
						});
					}

					// Set SSE headers
					res.writeHead(200, {
						'Content-Type': 'text/event-stream',
						'Cache-Control': 'no-cache',
						Connection: 'keep-alive',
						'Access-Control-Allow-Origin': requestOrigin,
						'Access-Control-Allow-Headers': 'Cache-Control',
						Vary: 'Origin',
					});

					const removeClient = sseService.addClient(userId, res);

					// Send initial connection event (Q-06: merged welcome into connected)
					res.write(`event: connected\n`);
					res.write(
						`data: ${JSON.stringify({
							message: 'Connected to notification stream',
							userId,
							timestamp: new Date().toISOString(),
						})}\n\n`,
					);

					// B-06: Removed deprecated req.on('aborted') — 'close' covers all disconnect cases
					req.on('close', () => {
						removeClient();
					});

					return res;
				} catch (error) {
					console.error('SSE connection error:', error);
					if (!res.headersSent) {
						return res.status(500).json({
							success: false,
							error: { code: 'SSE_ERROR', message: 'Failed to establish SSE connection' },
						});
					}
					return res;
				}
			},
		},
	};
};
