import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import { CHANNEL, CHANNELS } from '../../../../../models/channel.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import { EVENT, EVENTS } from '../../../../../models/event.ts';
import { FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/channels/:channel_id/events - get channel events
// query parameters:
//   partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PRECHECKS.GET = [get_session, get_user, require_user, async (_req: Request, meta: Record<string, any>): Promise<Response | undefined> => {
	const channel_id: string = meta.params?.channel_id?.toLowerCase().trim() ?? '';

	// lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
	const channel: CHANNEL | null = channel_id.length === 49 ? await CHANNELS.get(channel_id) : null;

	if (!channel) {
		return CANNED_RESPONSES.not_found();
	}

	meta.channel = channel;

	const channel_is_public: boolean = meta.channel.permissions.read.length === 0;
	const user_has_read_for_channel = channel_is_public || meta.channel.permissions.read.includes(meta.user.id);

	if (!user_has_read_for_channel) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function GET(request: Request, meta: Record<string, any>): Promise<Response> {
	const sorts = EVENTS.sorts;
	const sort_name: string = meta.query.sort ?? 'newest';
	const key = sort_name as keyof typeof sorts;
	const sort: any = sorts[key];
	if (!sort) {
		return Response.json({
			error: {
				message: 'You must specify a sort: newest, oldest, latest, stalest',
				cause: 'invalid_sort'
			}
		}, {
			status: 400
		});
	}

	const options: FSDB_SEARCH_OPTIONS<EVENT> = {
		...(meta.query ?? {}),
		limit: Math.min(parseInt(meta.query?.limit ?? '10', 10), 1_000),
		offset: Math.max(parseInt(meta.query?.offset ?? '0', 10), 0),
		sort,
		filter: (entry: WALK_ENTRY<EVENT>) => {
			const {
				event_type,
				event_id
			} = /^.*\/(?<event_type>.*?):(?<event_id>[A-Za-z-]+)\.json$/.exec(entry.path)?.groups ?? {};

			if (meta.query.after_id && event_id <= meta.query.after_id) {
				return false;
			}

			if (meta.query.before_id && event_id >= meta.query.before_id) {
				return false;
			}

			if (meta.query.type && !meta.query.type.split(',').includes(event_type)) {
				return false;
			}

			return true;
		}
	};

	const headers = {
		'Cache-Control': 'no-cache, must-revalidate'
	};

	const results = (await EVENTS.find({
		channel: meta.channel.id
	}, options))
		.map((entry: WALK_ENTRY<EVENT>) => entry.load())
		.sort((lhs_item: EVENT, rhs_item: EVENT) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));

	// long-polling support
	if (results.length === 0 && meta.query.wait) {
		return new Promise((resolve, reject) => {
			function on_create(create_event: any) {
				if (create_event.item.channel !== meta.channel.id) {
					return;
				}

				if (meta.query.type && !meta.query.type.split(',').includes(create_event.item.type)) {
					return;
				}

				results.push(create_event.item);
				clearTimeout(timeout);
				EVENTS.off('create', on_create);

				return resolve(Response.json(results, {
					status: 200,
					headers
				}));
			}

			const timeout = setTimeout(() => {
				EVENTS.off('create', on_create);
				return resolve(Response.json(results, {
					status: 200,
					headers
				}));
			}, 60_000); // 60 seconds
			EVENTS.on('create', on_create);
			request.signal.addEventListener('abort', () => {
				EVENTS.off('create', on_create);
				clearTimeout(timeout);
				reject(new Error('request aborted'));
			});
			Deno.addSignalListener('SIGINT', () => {
				EVENTS.off('create', on_create);
				clearTimeout(timeout);
				return resolve(Response.json(results, {
					status: 200,
					headers
				}));
			});
		});
	}

	return Response.json(results, {
		status: 200,
		headers
	});
}
