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

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/channels/:id - Get a channel
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);

	if (!user_has_read_for_channel) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export function GET(_req: Request, meta: Record<string, any>): Response {
	return Response.json(meta.channel, {
		status: 200
	});
}

// PUT /api/channels/:id - Update channel
PRECHECKS.PUT = [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 user_has_write_for_channel = channel.permissions.write.includes(meta.user.id);

	if (!user_has_write_for_channel) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function PUT(req: Request, meta: Record<string, any>): Promise<Response> {
	const now = new Date().toISOString();

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

		await CHANNELS.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/channels/:id - Delete channel
PRECHECKS.DELETE = [
	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 user_has_write_for_channel = channel.permissions.write.includes(meta.user.id);

		if (!user_has_write_for_channel) {
			return CANNED_RESPONSES.permission_denied();
		}
	}
];
export async function DELETE(_req: Request, meta: Record<string, any>): Promise<Response> {
	await CHANNELS.delete(meta.channel);

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