import lurid from '@andyburke/lurid';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../../utils/prechecks.ts';
import * as CANNED_RESPONSES from '../../../../../utils/canned_responses.ts';
import parse_body from '../../../../../utils/bodyparser.ts';
import { FSDB_SEARCH_OPTIONS, WALK_ENTRY } from '@andyburke/fsdb';
import { INVITE_CODE, INVITE_CODES, VALIDATE_INVITE_CODE } from '../../../../../models/invites.ts';

export const PRECHECKS: PRECHECK_TABLE = {};

const INVITE_CODES_ALLOWED_PER_MINUTE = parseInt(Deno.env.get('INVITE_CODES_ALLOWED_PER_MINUTE') ?? '3', 10);
const DEFAULT_INVITE_EXPIRE_TIME: number = 28 * 24 * 60 * 60 * 1_000; // 28 days max invite length

// GET /api/users/:user_id/invites - get invites 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_invites_permission = meta.user.permissions.includes('invites.read.own');
	const user_has_read_all_invites_permission = meta.user.permissions.includes('invites.read.all');

	if (!(user_has_read_all_invites_permission || (user_has_read_own_invites_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 = INVITE_CODES.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<INVITE_CODE> = {
		...(meta.query ?? {}),
		limit: Math.min(parseInt(meta.query?.limit ?? '10'), 1_000),
		sort,
		filter: (entry: WALK_ENTRY<INVITE_CODE>) => {
			if (meta.query.after_id && entry.path <= INVITE_CODES.get_organized_id_path(meta.query.after_id)) {
				return false;
			}

			if (meta.query.before_id && entry.path >= INVITE_CODES.get_organized_id_path(meta.query.before_id)) {
				return false;
			}

			return true;
		}
	};

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

	const results = (await INVITE_CODES.all(options))
		.map((entry: WALK_ENTRY<INVITE_CODE>) => entry.load())
		.sort((lhs_item: INVITE_CODE, rhs_item: INVITE_CODE) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));

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

// POST /api/users/:user_id/invites - Create an invite
PRECHECKS.POST = [get_session, get_user, require_user, (_request: Request, meta: Record<string, any>): Response | undefined => {
	const user_has_create_invites_permission = meta.user.permissions.includes('invites.create');

	if (!user_has_create_invites_permission) {
		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 invite_code: INVITE_CODE = {
			...body,
			id: lurid(),
			creator_id: meta.user.id,
			timestamps: {
				created: now
			}
		};

		if (typeof invite_code.code !== 'string' || invite_code.code.length === 0) {
			const full_lurid = lurid();
			invite_code.code = `${full_lurid.substring(0, 14).replace(/-/g, ' ')}${full_lurid.substring(39).replace(/-/g, ' ')}`;
		}

		invite_code.timestamps.expires = invite_code.timestamps.expires ?? new Date(new Date(now).valueOf() + DEFAULT_INVITE_EXPIRE_TIME).toISOString();

		const errors = VALIDATE_INVITE_CODE(invite_code);
		if (errors) {
			return Response.json({
				errors
			}, {
				status: 400
			});
		}

		const existing_code: INVITE_CODE | undefined = (await INVITE_CODES.find({ code: invite_code.code, limit: 1 })).shift()?.load();
		if (existing_code) {
			return Response.json({
				errors: [{
					cause: 'existing_invite_code',
					message: 'That secret code has already been used.'
				}]
			}, {
				status: 400
			});
		}

		const recent_codes: INVITE_CODE[] = (await INVITE_CODES.find({
			creator_id: invite_code.code,
			sort: INVITE_CODES.sorts.newest,
			limit: INVITE_CODES_ALLOWED_PER_MINUTE
		})).map((entry) => entry.load());

		const one_minute_ago = new Date(new Date(now).getTime() - 60_000).toISOString();
		const codes_from_the_last_minute = recent_codes.filter((code) => (code.timestamps.created > one_minute_ago));

		if (codes_from_the_last_minute.length >= INVITE_CODES_ALLOWED_PER_MINUTE) {
			return Response.json({
				errors: [{
					cause: 'excessive_invite_code_generation',
					message: 'Invite code creation is time limited, please be patient.'
				}]
			}, {
				status: 400
			});
		}

		await INVITE_CODES.create(invite_code);

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