<?php
namespace App\Alias;

use PDO;
use PDOException;

class Connection
{
    public function __construct(
        protected string $host,
        protected string $database,
        protected string $username,
        protected string $password,
        protected ?int $port = null,
        protected int $retries = 5
    ) {}

    protected PDO $connection;
    public function connect(): PDO
    {
        if (!isset($this->connection)) {
            $r = 0;
            $exception = null;
            while ($r < $this->retries) {
                try {
                    $dsn = $this->getDsn();
                    $this->connection = new PDO($dsn, $this->username, $this->password);
                    return $this->connection;
                } catch (PDOException $e) {
                    if ($exception !== null) {
                        $e = new PDOException($e->getMessage(), $e->getCode(), $exception);
                    }
                    $exception = $e;
                    usleep(500);
                }
                $r ++;
            }
            throw $exception;
        }
        return $this->connection;
    }
    protected function getDsn(): string
    {
        $dsn = "mysql:host={$this->host};dbname={$this->database}";
        if (isset($this->port)) {
            $dsn .= ";port={$this->port}";
        }
        return $dsn;
    }
}
