<?php

namespace Velis\User;

use DomainException;
use Velis\App;
use Velis\Arrays;
use Velis\Lang;
use Velis\User;

class UserProvider
{
    /**
     * @var class-string<User>
     */
    private string $userClass;

    public function __construct()
    {
        $this->userClass = App::$config->settings->userClass ?: User::class;
    }

    /**
     * @throws DomainException
     */
    public function getUser(int $userId): User
    {
        $user = Arrays::getFirst($this->getUsers([$userId]));

        if (!$user instanceof $this->userClass) {
            throw new DomainException(Lang::get('USER_NOT_FOUND'));
        }

        return $user;
    }

    /**
     * @param array<int> $userIds
     * @return array<User>
     */
    public function getUsers(array $userIds): array
    {
        if ($this->userClass::isCacheable()) {
            $users = $this->userClass::get($userIds);
        } else {
            $users = $this->userClass::bufferedInstance($userIds);
        }

        $notFoundIds = array_diff($userIds, array_keys($users));
        if (count($notFoundIds) > 0) {
            throw new DomainException(Lang::get('USER_NOT_FOUND'));
        }

        return $users;
    }

    /**
     * @param array<string,mixed> $data
     */
    public function createUser(array $data): User
    {
        return new $this->userClass($data);
    }
}
