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

export const PRECHECKS: PRECHECK_TABLE = {};

// GET /api/users/:user_id/signups - see signups that have resulted from this user
// 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_signups_permission = meta.user.permissions.includes('signups.read.own');
	const user_has_read_all_signups_permission = meta.user.permissions.includes('signups.read.all');

	if (!(user_has_read_all_signups_permission || (user_has_read_own_signups_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<SIGNUP> = {
		...(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 SIGNUPS.all(options))
		.map((entry: WALK_ENTRY<SIGNUP>) => entry.load())
		.sort((lhs_item: SIGNUP, rhs_item: SIGNUP) => rhs_item.timestamps.created.localeCompare(lhs_item.timestamps.created));

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