<?php

declare(strict_types=1);

namespace FecaMailshots\Infrastructure;

use PDO;

final class PdoDatabaseRouter implements DatabaseRouter
{
    private PDO $mailshotsPdo;

    private PDO $membersPdo;

    private string $mailshotsDbName;

    private string $membersDbName;

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

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

        $common = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
        ];

        $this->mailshotsPdo = new PDO(
            sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $this->mailshotsDbName),
            $user,
            $pass,
            $common
        );

        $this->membersPdo = new PDO(
            sprintf('mysql:host=%s;port=%s;dbname=%s;charset=utf8mb4', $host, $port, $this->membersDbName),
            $user,
            $pass,
            $common
        );
    }

    public function mailshotsPdo(): PDO
    {
        return $this->mailshotsPdo;
    }

    public function membersPdo(): PDO
    {
        return $this->membersPdo;
    }

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

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

    /** @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];
    }
}
