/**
 * C-05: SSE subscribe endpoint — CORS origin whitelist
 * Tests the CORS origin selection logic extracted from the subscribe handler.
 */

import express from 'express';
import request from 'supertest';

const buildApp = () => {
	const app = express();
	// Inline the CORS logic from the controller (unit testing the logic directly)
	app.get('/sse', (req: any, res: any) => {
		const allowedOrigins = (process.env.FRONTEND_URL || '')
			.split(',')
			.map((o: string) => o.trim())
			.filter(Boolean);
		const requestOrigin = req.headers.origin || '';
		const allowedOrigin =
			allowedOrigins.length === 0 || allowedOrigins.includes(requestOrigin) ? requestOrigin || '*' : allowedOrigins[0];

		res.writeHead(200, {
			'Content-Type': 'text/event-stream',
			'Cache-Control': 'no-cache',
			Connection: 'keep-alive',
			'Access-Control-Allow-Origin': allowedOrigin,
			...(allowedOrigin !== '*' ? { Vary: 'Origin' } : {}),
		});
		res.end();
	});
	return app;
};

describe('SSE CORS origin whitelist (C-05)', () => {
	const originalEnv = process.env.FRONTEND_URL;

	afterEach(() => {
		process.env.FRONTEND_URL = originalEnv;
	});

	it('allows exact whitelisted origin', async () => {
		process.env.FRONTEND_URL = 'https://app.example.com';
		const res = await request(buildApp()).get('/sse').set('Origin', 'https://app.example.com');
		expect(res.headers['access-control-allow-origin']).toBe('https://app.example.com');
		expect(res.headers['vary']).toBe('Origin');
	});

	it('rejects origin not in whitelist — returns first allowed origin instead', async () => {
		process.env.FRONTEND_URL = 'https://app.example.com';
		const res = await request(buildApp()).get('/sse').set('Origin', 'https://attacker.com');
		expect(res.headers['access-control-allow-origin']).toBe('https://app.example.com');
		expect(res.headers['access-control-allow-origin']).not.toBe('https://attacker.com');
	});

	it('allows any origin when FRONTEND_URL is empty (development fallback)', async () => {
		process.env.FRONTEND_URL = '';
		const res = await request(buildApp()).get('/sse').set('Origin', 'http://localhost:3000');
		expect(res.headers['access-control-allow-origin']).toBe('http://localhost:3000');
	});

	it('falls back to * when FRONTEND_URL is empty and no origin header', async () => {
		process.env.FRONTEND_URL = '';
		const res = await request(buildApp()).get('/sse');
		expect(res.headers['access-control-allow-origin']).toBe('*');
	});

	it('supports comma-separated FRONTEND_URL list', async () => {
		process.env.FRONTEND_URL = 'https://app.example.com, https://admin.example.com';
		const res = await request(buildApp()).get('/sse').set('Origin', 'https://admin.example.com');
		expect(res.headers['access-control-allow-origin']).toBe('https://admin.example.com');
	});
});
