import type { Permissions } from '$lib/permissions';
import type { Cookies } from '@sveltejs/kit';
import * as crypto from 'crypto';
import type { Admin } from '$lib/server/database';

export interface Session {
	sessionId: string;
	userId: number;
	permissions: Permissions;
}

let sessions: Session[] = [];

function sessionFromId(sessionId: string | Cookies): Session | null {
	const sessId = sessionIdFromStringOrCookies(sessionId);
	return sessions.find((v) => v.sessionId == sessId) || null;
}

function sessionIdFromStringOrCookies(input: string | Cookies): string | null {
	return typeof input == 'string' ? input : input.get('session') || null;
}

export function addSession(user: { id: number; permissions: Permissions } | Admin): string {
	const session = crypto.randomBytes(16).toString('hex');
	sessions.push({
		sessionId: session,
		userId: user.id,
		permissions: user.permissions
	});
	return session;
}

export function getSession(
	sessionId: string | Cookies,
	options?: { permissions?: number[] }
): Session | null {
	const session = sessionFromId(sessionId);
	if (!session) {
		return null;
	}
	for (const perm of options?.permissions || []) {
		if ((session.permissions.value & perm) == 0) {
			return null;
		}
	}
	return session;
}

export function updateAllUserSessions(userId: number, options: { permissions: Permissions }) {
	for (const session of sessions.filter((v) => v.userId == userId)) {
		session.permissions = options.permissions;
	}
}

export function deleteSession(sessionId: string | Cookies) {
	const session = sessionFromId(sessionId);
	if (session) {
		sessions.splice(sessions.indexOf(session), 1);
	}
}

export function deleteAllUserSessions(userId: number) {
	sessions = sessions.filter((v) => v.userId != userId);
}
