<?php

declare(strict_types=1);

final class UserFingerprintsGetController extends AbstractController
{
	protected string $route = '/api/v1/user/{userId}/fingerprints';

	private int $userId;

	public function __construct(string $url)
	{
		parent::__construct($url);
		$this->userId = (int)$this->getUrlParamInt('userId');
	}

	public function handle(): void
	{
		if (!$this->isUserLoggedIn() ) {
			return;
		}

		try {
			$this->response = new ApiJsonResponse();

			$user = new User($this->userId);

			if (!$this->hasUserPermission($this->userId)) {
				if (!$user->isSharingWith($this->session->getUserId())) {
					return;
				}
			}

			$fingerprints = new FingerprintCollection();

			foreach ($user->getFingerprintIds() as $fingerprintId) {
				$fingerprints->add(new Fingerprint($fingerprintId));
			}

			$this->response->setParameter('fingerprints', $fingerprints->jsonSerialize());
		} catch (Throwable $e) {
			$this->response->setParameter('success', false);
			$this->response->setMessage($e->getMessage());
			$this->response->setStatus($e->getCode() !== 0 ? $e->getCode() : ServerStatus::BAD_REQUEST);
		}
	}
}