<?php

namespace App\Model\Database;

use Nette\Database\Connection;
use Nette\Database\Explorer;
use Nette\Database\Structure;
use Nette\Caching\Storages\MemoryStorage;
use Nette\Security\User;

class KufrikConnectionFactory
{
    private User $user;
    private string $dbUser;
    private string $dbPassword;

    public function __construct(string $dbUser, string $dbPassword, User $user)
    {
        $this->dbUser = $dbUser;
        $this->dbPassword = $dbPassword;
        $this->user = $user;
    }

    public function createConnection(): Connection
    {
        if (!$this->user->isLoggedIn()) {
            throw new \LogicException('Uživatel není přihlášen.');
        }

        $identity = $this->user->getIdentity();

        // Server i Databáze se načtou z Identity přihlášeného uživatele (z tabulky LOGIN)
        $host = $identity->server ?? null;
        $databaseName = $identity->database ?? null;

        if (empty($host) || empty($databaseName)) {
            throw new \LogicException('Přihlášený uživatel nemá v tabulce LOGIN definovaný SERVER nebo DATABASE.');
        }

        // Dynamický DSN řetězec
        $dsn = "sqlsrv:Server={$host};Database={$databaseName};LoginTimeout=3;";

        return new Connection(
            $dsn,
            $this->dbUser,
            $this->dbPassword,
            [
                'lazy' => false,
                'driverOptions' => [
                    \PDO::SQLSRV_ATTR_ENCODING => \PDO::SQLSRV_ENCODING_UTF8,
                ]
            ]
        );
    }

    public function createExplorer(): Explorer
    {
        $connection = $this->createConnection();
        $storage = new MemoryStorage();
        $structure = new Structure($connection, $storage);

        return new Explorer($connection, $structure);
    }
}