<?php

use Vn\Web;

class Supplant extends Vn\Web\JsonRequest {
	const PARAMS = ['supplantUser'];

	function run($db) {
		$userId = $db->getValue(
			'SELECT id FROM account.user WHERE `name` = #',
			[$_REQUEST['supplantUser']]
		);

		$isClient = $db->getValue(
			'SELECT COUNT(*) > 0 FROM vn.client WHERE id = #',
			[$userId]
		);
		if (!$isClient)
			throw new Web\ForbiddenException(s('The user is not a client'));

		$hasAccount = $db->getValue(
			'SELECT COUNT(*) > 0 FROM account.account WHERE id = #',
			[$userId]
		);
		if ($hasAccount)
			throw new Web\ForbiddenException(s('The user is not impersonable'));

		return $this->service->createToken($_REQUEST['supplantUser']);
	}
}
