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

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/channels/:channel_id/events/:id - Get an event
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 = channel.permissions.read.length === 0;
	const user_has_read_for_channel = channel_is_public || channel.permissions.read.includes(meta.user.id);
	const channel_has_public_events = user_has_read_for_channel && (channel.permissions.events.read.length === 0);
	const user_has_read_events_for_channel = user_has_read_for_channel &&
		(channel_has_public_events || channel.permissions.events.read.includes(meta.user.id));

	if (!user_has_read_events_for_channel) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
	const event: EVENT | null = await EVENTS.get(meta.params.event_id);

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

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