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 - Update (APPEND_ONLY_EVENTS)',
	permissions: {
		env: true,
		read: true,
		write: true,
		net: true
	},
	fn: async () => {
		let test_server_info: EPHEMERAL_SERVER | null = null;
		try {
			Deno.env.set('APPEND_ONLY_EVENTS', 'true');
			asserts.assert(Deno.env.get('APPEND_ONLY_EVENTS'));

			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 update events channel in append only mode'
				}
			});

			asserts.assert(channel);

			const event_from_owner = 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: {
						foo: 'bar'
					}
				}
			});

			asserts.assert(event_from_owner);

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

			asserts.assertEquals(fetched_event_from_owner, event_from_owner);

			try {
				await client.fetch(`/events/${event_from_owner.id}`, {
					method: 'PUT',
					headers: {
						'x-session_id': owner_info.session.id,
						'x-totp': await generateTotp(owner_info.session.secret)
					},
					json: {
						meta: {
							foo: 'bar'
						}
					}
				});

				asserts.fail('allowed updating an event in a channel with APPEND_ONLY_EVENTS on');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'append_only_events');
			}

			try {
				await client.fetch(`/events/${event_from_owner.id}`, {
					method: 'DELETE',
					headers: {
						'x-session_id': owner_info.session.id,
						'x-totp': await generateTotp(owner_info.session.secret)
					}
				});

				asserts.fail('allowed deleting an event in a channel with APPEND_ONLY_EVENTS on');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'append_only_events');
			}

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

			const event_from_other_user = await client.fetch(`/events`, {
				method: 'POST',
				headers: {
					'x-session_id': other_user_info.session.id,
					'x-totp': await generateTotp(other_user_info.session.secret)
				},
				json: {
					type: 'test',
					channel: channel.id,
					data: {
						other_user: true
					}
				}
			});

			asserts.assert(event_from_other_user);

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

			asserts.assertEquals(fetched_event_from_other_user, event_from_other_user);

			try {
				await client.fetch(`/events/${event_from_other_user.id}`, {
					method: 'PUT',
					headers: {
						'x-session_id': other_user_info.session.id,
						'x-totp': await generateTotp(other_user_info.session.secret)
					},
					json: {
						meta: {
							foo: 'bar'
						}
					}
				});

				asserts.fail('allowed updating an event in a channel with APPEND_ONLY_EVENTS on');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'append_only_events');
			}

			try {
				await client.fetch(`/events/${event_from_other_user.id}`, {
					method: 'DELETE',
					headers: {
						'x-session_id': other_user_info.session.id,
						'x-totp': await generateTotp(other_user_info.session.secret)
					}
				});

				asserts.fail('allowed deleting an event in a channel with APPEND_ONLY_EVENTS on');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'append_only_events');
			}

			await delete_user(client, other_user_info);
			await delete_user(client, owner_info);
		} finally {
			Deno.env.delete('APPEND_ONLY_EVENTS');

			if (test_server_info) {
				await test_server_info?.server?.stop();
			}
		}
	}
});
