<?php

declare(strict_types=1);

namespace FecaMailshots\Infrastructure;

use PDO;

final class PdoDatabaseRouter implements DatabaseRouter
{
    private ?PDO $mailshotsPdo = null;

    private ?PDO $membersPdo = null;

    private string $mailshotsDbName;

    private string $membersDbName;

    private string $fenDbName;

    private string $host;
    private string $port;
    private string $user;
    private string $pass;
    /** @var array<int, mixed> */
    private array $pdoOptions;

    /** @param array<string, string> $config */
    public function __construct(array $config)
    {
        $this->host = self::required($config, 'MYSQL_HOST');
        $this->port = self::required($config, 'MYSQL_PORT');
        $this->user = self::required($config, 'MYSQL_USER');
        $this->pass = self::required($config, 'MYSQL_PASSWORD');

        $this->mailshotsDbName = self::required($config, 'MAILSHOTS_REMOTE_MYSQL_DB');
        $this->membersDbName = self::required($config, 'MEMBERS_REMOTE_MYSQL_DB');
        $this->fenDbName = self::required($config, 'FEN_REMOTE_MYSQL_DB');

        $this->pdoOptions = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
        ];
    }

    public function mailshotsPdo(): PDO
    {
        if ($this->mailshotsPdo === null) {
            $this->mailshotsPdo = $this->connect($this->mailshotsDbName);
        }
        return $this->mailshotsPdo;
    }

    public function membersPdo(): PDO
    {
        if ($this->membersPdo === null) {
            $this->membersPdo = $this->connect($this->membersDbName);
        }
        return $this->membersPdo;
    }

    public function mailshotsDbName(): string
    {
        return $this->mailshotsDbName;
    }

    public function membersDbName(): string
    {
        return $this->membersDbName;
    }

    public function fenDbName(): string
    {
        return $this->fenDbName;
    }

    /** @param array<string, string> $config */
    private static function required(array $config, string $key): string
    {
        if (!isset($config[$key]) || $config[$key] === '') {
            throw new \RuntimeException('Missing DB config key: ' . $key);
        }
        return $config[$key];
    }

    private function connect(string $dbName): PDO
    {
        return new PDO(
            sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $this->host, $this->port, $dbName),
            $this->user,
            $this->pass,
            $this->pdoOptions
        );
    }
}
