/* eslint-disable no-param-reassign */
import { stringify } from '@brillout/json-serializer/stringify'; /* eslint-disable-line import/extensions */
import IPCIDR from 'ip-cidr';
import argv from '../argv.js';

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

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

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) {
		req.user = req.session.user;
		req.user.ip = ip;
	}

	next();
}

export async function updateSessionUser(req) {
	const user = 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 = 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 = user;
	res.send(user);
}

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

	res.send(stringify(keys));
}

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

	res.send(stringify(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();
}
/* eslint-enable no-param-reassign */
