/* eslint-disable no-param-reassign */
import IPCIDR from 'ip-cidr';

import { login, signup } from '../auth.js';

function getIp(req) {
	const ip = req.headers['x-forwarded-for']?.split(',')[0] || req.connection.remoteAddress; // See src/ws

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

	// 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 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);
}
/* eslint-enable no-param-reassign */
