<?php

declare(strict_types=1);

namespace App\Services;

use RuntimeException;

/**
 * Resolves DIAR-owned Oracle schemas without DB links.
 *
 * The returned value is the existing hospital connection key understood by
 * App\Core\Database. No credentials are stored or duplicated here.
 */
final class DiarConnectionResolver
{
    /** @var array<string,string> */
    private const SITE_CONNECTIONS = [
        'NJCH' => 'njch',
        'MNH' => 'mnh',
    ];

    /** @param array<int,string> $allowedSites @return array<int,string> */
    public function normalizeAllowedSites(array $allowedSites): array
    {
        $normalized = [];
        foreach ($allowedSites as $site) {
            $site = strtoupper(trim((string)$site));
            if (isset(self::SITE_CONNECTIONS[$site]) && !in_array($site, $normalized, true)) {
                $normalized[] = $site;
            }
        }
        return $normalized;
    }

    /** @param array<int,string> $allowedSites @return array<int,string> */
    public function requestedSites(string $requestedSite, array $allowedSites): array
    {
        $allowed = $this->normalizeAllowedSites($allowedSites);
        if ($allowed === []) {
            throw new RuntimeException('DIAR_NO_ALLOWED_SITES');
        }

        $requestedSite = strtoupper(trim($requestedSite));
        if ($requestedSite === '' || $requestedSite === 'ALL' || $requestedSite === 'COMBINED') {
            return $allowed;
        }
        if (!in_array($requestedSite, $allowed, true)) {
            throw new RuntimeException('DIAR_SITE_NOT_ALLOWED');
        }
        return [$requestedSite];
    }

    public function connectionFor(string $site): string
    {
        $site = strtoupper(trim($site));
        if (!isset(self::SITE_CONNECTIONS[$site])) {
            throw new RuntimeException('DIAR_UNSUPPORTED_SITE');
        }
        return self::SITE_CONNECTIONS[$site];
    }
}
