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

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/events/:id - Get an event
PRECHECKS.GET = [get_session, get_user, require_user];
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
	});
}

// PUT /api/events/:event_id - Update event
PRECHECKS.PUT = [
	get_session,
	get_user,
	require_user,
	(_req: Request, _meta: Record<string, any>): Response | undefined => {
		if (Deno.env.get('APPEND_ONLY_EVENTS')) {
			return CANNED_RESPONSES.append_only_events();
		}
	},
	(_req: Request, meta: Record<string, any>): Response | undefined => {
		if (!meta.user.permissions.some((permission: string) => permission.indexOf('events.write') === 0)) {
			return CANNED_RESPONSES.permission_denied();
		}
	}
];
export async function PUT(req: Request, meta: Record<string, any>): Promise<Response> {
	const now = new Date().toISOString();

	try {
		const event: EVENT | null = await EVENTS.get(meta.params.event_id);

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

		if (event.creator_id !== meta.user.id) {
			return CANNED_RESPONSES.permission_denied();
		}

		const body = await parse_body(req);
		const updated: EVENT = {
			...event,
			...body,
			id: event.id,
			creator_id: event.creator_id,
			channel: event.channel,
			timestamps: {
				created: event.timestamps.created,
				updated: now
			}
		};

		if (updated.channel) {
			const channel: CHANNEL | null = await CHANNELS.get(updated.channel);
			if (!channel) {
				return Response.json({
					errors: [{
						cause: 'missing_channel',
						message: 'No such channel exists.'
					}]
				}, {
					status: 400
				});
			}

			const user_can_write_events_to_channel = channel.permissions.events.write.length === 0 ? true : channel.permissions.events.write.includes(meta.user.id);

			if (!user_can_write_events_to_channel) {
				return CANNED_RESPONSES.permission_denied();
			}
		}

		if (!user_has_write_permission_for_event(meta.user, updated)) {
			return CANNED_RESPONSES.permission_denied();
		}

		await EVENTS.update(updated);
		return Response.json(updated, {
			status: 200
		});
	} catch (err) {
		return Response.json({
			error: {
				message: (err as Error)?.message ?? 'Unknown error due to invalid data.',
				cause: (err as Error)?.cause ?? 'invalid_data'
			}
		}, {
			status: 400
		});
	}
}

// DELETE /api/events/:event_id - Delete event
PRECHECKS.DELETE = [
	get_session,
	get_user,
	require_user,
	(_req: Request, _meta: Record<string, any>): Response | undefined => {
		if (Deno.env.get('APPEND_ONLY_EVENTS')) {
			return CANNED_RESPONSES.append_only_events();
		}
	},
	(_req: Request, meta: Record<string, any>): Response | undefined => {
		if (!meta.user.permissions.some((permission: string) => permission.indexOf('events.write') === 0)) {
			return CANNED_RESPONSES.permission_denied();
		}
	}
];
export async function DELETE(_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();
	}

	if (event.channel) {
		const channel: CHANNEL | null = await CHANNELS.get(event.channel);
		if (!channel) {
			return Response.json({
				errors: [{
					cause: 'missing_channel',
					message: 'No such channel exists.'
				}]
			}, {
				status: 400
			});
		}

		const user_can_write_events_to_channel = channel.permissions.events.write.length === 0 ? true : channel.permissions.events.write.includes(meta.user.id);

		if (!user_can_write_events_to_channel) {
			return CANNED_RESPONSES.permission_denied();
		}
	}

	if (!user_has_write_permission_for_event(meta.user, event)) {
		return CANNED_RESPONSES.permission_denied();
	}

	await EVENTS.delete(event);

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