import crypto from 'node:crypto';
import IPCIDR from 'ip-cidr';
import argv from '../argv.js';

import {
	createKey,
	fetchUserKeys,
	flushUserKeys,
	login,
	removeUserKey,
	signup,
} from '../auth.js';

import { fetchUser } from '../users.js';

// changes every time the process restarts, so a deploy invalidates all cached session users
// even if they're within the staleness window below
const runtimeId = crypto.randomUUID();
const sessionStaleThreshold = 5 * 60 * 1000;

// spread into a new object rather than mutating the user we're about to hand back to the
// client (loginApi/signupApi send this straight to the browser) — runtimeId/refreshedAt are
// session bookkeeping only, they shouldn't leak into the API response
function toSession(user) {
	return {
		...user,
		runtimeId,
		refreshedAt: Date.now(),
	};
}

function isSessionStale(sessionUser) {
	return sessionUser.runtimeId !== runtimeId || Date.now() - sessionUser.refreshedAt > sessionStaleThreshold;
}

// concurrent requests for the same user (e.g. the burst of asset/API requests a single page
// load fires) share one in-flight refresh instead of each independently hitting the DB
const pendingSessionRefreshes = new Map();

async function refreshSessionUser(sessionUser) {
	const pending = pendingSessionRefreshes.get(sessionUser.id);

	if (pending) {
		return pending;
	}

	const refresh = fetchUser(sessionUser.id, {}, sessionUser)
		.then((user) => toSession(user))
		.finally(() => pendingSessionRefreshes.delete(sessionUser.id));

	pendingSessionRefreshes.set(sessionUser.id, refresh);

	return refresh;
}

function getIp(req) {
	if (argv.ip) {
		return argv.ip;
	}

	const ip = req.headers['x-forwarded-for']?.split(',')[0] || req.connection.remoteAddress;

	const unmappedIp = ip?.includes('.')
		? ip.slice(ip.lastIndexOf(':') + 1)
		: ip;

	if (!unmappedIp) {
		console.log('failed unmapped ip', ip, unmappedIp);
		return null;
	}

	// ensure IP is in expanded notation for consistency and matching
	const expandedIp = unmappedIp.includes(':')
		? new IPCIDR(`${ip}/128`) // IPv6
		: new IPCIDR(`${ip}/32`); // IPv4

	if (!expandedIp.addressStart?.addressMinusSuffix) {
		throw new Error(`Could not determine user IP from ${ip}`);
	}

	return expandedIp.addressStart?.addressMinusSuffix || null;
}

export async function setUserApi(req, res, next) {
	const ip = getIp(req);

	req.userIp = ip;

	if (req.session.user) {
		if (isSessionStale(req.session.user)) {
			req.session.user = await refreshSessionUser(req.session.user);
		}

		req.user = req.session.user;
		req.user.ip = ip;
	}

	next();
}

export async function updateSessionUser(req) {
	const user = toSession(await fetchUser(req.session.user.id, {}, req.session.user));

	req.session.user = user;

	req.user = user;
	req.user.ip = req.userIp;
}

export async function loginApi(req, res) {
	const user = await login(req.body, req.userIp);

	req.session.user = toSession(user);
	res.send(user);
}

export async function logoutApi(req, res) {
	req.session.destroy((error) => {
		if (error) {
			res.status(500).send();
		}

		res.status(204).send();
	});
}

export async function signupApi(req, res) {
	const user = await signup(req.body, req.userIp);

	req.session.user = toSession(user);
	res.send(user);
}

export async function fetchUserKeysApi(req, res) {
	const keys = await fetchUserKeys(req.user);

	res.send(keys);
}

export async function createKeyApi(req, res) {
	const key = await createKey(req.user);

	res.send(key);
}

export async function removeUserKeyApi(req, res) {
	await removeUserKey(req.user, req.params.keyIdentifier);

	res.status(204).send();
}

export async function flushUserKeysApi(req, res) {
	await flushUserKeys(req.user);

	res.status(204).send();
}
