import * as asserts from '@std/assert';
import { delete_user, EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from './helpers.ts';
import { api, API_CLIENT } from '../utils/api.ts';
import { generateTotp } from '../utils/totp.ts';

Deno.test({
	name: 'API - CHANNELS - EVENTS - Get',
	permissions: {
		env: true,
		read: true,
		write: true,
		net: true
	},

	// TODO: see severus, but why do we need this?
	sanitizeResources: false,
	sanitizeOps: false,

	fn: async () => {
		let test_server_info: EPHEMERAL_SERVER | null = null;
		try {
			test_server_info = await get_ephemeral_listen_server();
			const client: API_CLIENT = api({
				prefix: '/api',
				hostname: test_server_info.hostname,
				port: test_server_info.port
			});

			const owner_info = await get_new_user(client);

			await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'channels.create']);

			const channel = await client.fetch('/channels', {
				method: 'POST',
				headers: {
					'x-session_id': owner_info.session.id,
					'x-totp': await generateTotp(owner_info.session.secret)
				},
				json: {
					name: 'test get events channel'
				}
			});

			asserts.assert(channel);

			const NUM_INITIAL_EVENTS = 5;
			const events_initial_batch: any[] = [];
			for (let i = 0; i < NUM_INITIAL_EVENTS; ++i) {
				const event = await client.fetch(`/events`, {
					method: 'POST',
					headers: {
						'x-session_id': owner_info.session.id,
						'x-totp': await generateTotp(owner_info.session.secret)
					},
					json: {
						type: 'test',
						channel: channel.id,
						data: {
							i
						}
					}
				});

				asserts.assert(event);
				events_initial_batch.push(event);
			}

			asserts.assertEquals(events_initial_batch.length, NUM_INITIAL_EVENTS);

			const other_user_info = await get_new_user(client, {}, owner_info);

			const events_from_server = await client.fetch(`/channels/${channel.id}/events`, {
				method: 'GET',
				headers: {
					'x-session_id': other_user_info.session.id,
					'x-totp': await generateTotp(other_user_info.session.secret)
				}
			});

			asserts.assertEquals(events_from_server.length, NUM_INITIAL_EVENTS);

			const newest_event = events_from_server[0];
			asserts.assert(newest_event);

			const long_poll_request_promise = client.fetch(`/channels/${channel.id}/events?wait=true&after_id=${newest_event.id.split(':', 2)[1]}`, {
				method: 'GET',
				headers: {
					'x-session_id': other_user_info.session.id,
					'x-totp': await generateTotp(other_user_info.session.secret)
				}
			});

			const wait_and_then_create_an_event = new Promise((resolve) => {
				setTimeout(async () => {
					await client.fetch(`/events`, {
						method: 'POST',
						headers: {
							'x-session_id': owner_info.session.id,
							'x-totp': await generateTotp(owner_info.session.secret)
						},
						json: {
							type: 'test',
							channel: channel.id,
							data: {
								i: 12345
							}
						}
					});

					resolve(undefined);
				}, 2_000);
			});

			await Promise.all([long_poll_request_promise, wait_and_then_create_an_event]).then((values) => {
				const long_polled_events = values.shift();
				asserts.assert(Array.isArray(long_polled_events));
				asserts.assertEquals(long_polled_events.length, 1);
				asserts.assertEquals(long_polled_events[0].data?.i, 12345);
			});

			await delete_user(client, other_user_info);
			await delete_user(client, owner_info);
		} finally {
			if (test_server_info) {
				await test_server_info.server.stop();
			}
		}
	}
});
