import { FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
import { WATCH, WATCHES } from '../../../../../models/watch.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import parse_body from '../../../../../utils/bodyparser.ts';
import lurid from '@andyburke/lurid';
import { CHANNELS } from '../../../../../models/channel.ts';

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/users/:user_id/watches - get watches this user has created
// 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, (_req: Request, meta: Record<string, any>): Response | undefined => {
	const user_has_read_own_watches_permission = meta.user.permissions.includes('watches.read.own');
	const user_has_read_all_watches_permission = meta.user.permissions.includes('watches.read.all');

	if (!(user_has_read_all_watches_permission || (user_has_read_own_watches_permission && meta.user.id === meta.params.user_id))) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function GET(_request: Request, meta: Record<string, any>): Promise<Response> {
	const sorts = WATCHES.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<WATCH> = {
		...(meta.query ?? {}),
		limit: Math.min(parseInt(meta.query?.limit ?? '100', 10), 1_000),
		sort,
		filter: (entry: WALK_ENTRY<WATCH>) => {
			const {
				event_type,
				event_id
			} = /^.*\/watches\/(?<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 WATCHES.all(options))
		.map((entry: WALK_ENTRY<WATCH>) => entry.load())
		.sort((lhs_item: WATCH, rhs_item: WATCH) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));

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

// POST /api/users/:user_id/watches - Create a watch
PRECHECKS.POST = [get_session, get_user, require_user, (_request: Request, meta: Record<string, any>): Response | undefined => {
	const user_has_create_own_watches_permission = meta.user.permissions.includes('watches.create.own');
	const user_has_create_all_watches_permission = meta.user.permissions.includes('watches.create.all');

	if (!(user_has_create_all_watches_permission || (user_has_create_own_watches_permission && meta.user.id === meta.params.user_id))) {
		return CANNED_RESPONSES.permission_denied();
	}
}];
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
	try {
		const now = new Date().toISOString();

		const body = await parse_body(req);
		const watch: WATCH = {
			...body,
			id: lurid(),
			creator_id: meta.user.id,
			timestamps: {
				created: now,
				updated: now
			}
		};

		if (watch.channel) {
			const channel = await CHANNELS.get(watch.channel);
			if (!channel) {
				return Response.json({
					errors: [{
						cause: 'invalid_channel_id',
						message: 'Could not find a channel with id: ' + watch.channel
					}]
				}, {
					status: 400
				});
			}
		}

		await WATCHES.create(watch);

		return Response.json(watch, {
			status: 201
		});
	} catch (error) {
		return Response.json({
			error: {
				message: (error as Error).message ?? 'Unknown Error!',
				cause: (error as Error).cause ?? 'unknown'
			}
		}, { status: 500 });
	}
}
