<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Services\BranchOracleAccessResolver;

$format = strtolower((string)($_GET['format'] ?? 'json'));

$remote = (string)($_SERVER['REMOTE_ADDR'] ?? '');
$isLocal = in_array($remote, ['127.0.0.1', '::1', 'localhost', ''], true);
$providedToken = (string)($_GET['token'] ?? '');
$expectedToken = trim((string)env('DDB_QA_TOKEN', ''));
$tokenOk = $expectedToken !== '' && hash_equals($expectedToken, $providedToken);

if (!$isLocal && !$tokenOk) {
    http_response_code(403);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode(['status' => 'FAIL', 'error' => 'Forbidden']);
    exit;
}

$branches = ['njch', 'jckh', 'mnh'];
$expected = [
    'njch' => ['connect_type' => 'sid', 'host' => '10.10.12.10', 'port' => '1521', 'sid' => 'ORANJC'],
    'jckh' => ['connect_type' => 'sid', 'host' => '10.11.42.10', 'port' => '1521', 'sid' => 'orajck'],
    'mnh' => ['connect_type' => 'sid', 'host' => '10.20.104.20', 'port' => '1521', 'sid' => 'oramnh'],
];

$checks = [];
$branchResults = [];
$resolver = new BranchOracleAccessResolver();

$add = static function (string $name, bool $ok, string $detail = '') use (&$checks): void {
    $checks[] = [
        'name' => $name,
        'status' => $ok ? 'PASS' : 'FAIL',
        'detail' => $detail,
    ];
};

foreach ($branches as $branch) {
    $db = (array)config('hospitals.' . $branch . '.database', []);
    $actual = [
        'connect_type' => strtolower(trim((string)($db['connect_type'] ?? ''))),
        'host' => trim((string)($db['host'] ?? '')),
        'port' => trim((string)($db['port'] ?? '')),
        'sid' => trim((string)($db['sid'] ?? '')),
        'username_present' => trim((string)($db['username'] ?? '')) !== '',
        'password_present' => trim((string)($db['password'] ?? '')) !== '',
    ];

    $expectedBranch = $expected[$branch];
    $contractOk = (
        $actual['connect_type'] === 'sid'
        && $actual['host'] === $expectedBranch['host']
        && $actual['port'] === $expectedBranch['port']
        && strcasecmp($actual['sid'], $expectedBranch['sid']) === 0
        && $actual['username_present']
        && $actual['password_present']
    );

    $add(
        $branch . '_authoritative_sid_config',
        $contractOk,
        $actual['connect_type'] . '://'
        . $actual['host'] . ':' . $actual['port']
        . '/SID=' . $actual['sid']
        . '; username=' . ($actual['username_present'] ? 'present' : 'missing')
        . '; password=' . ($actual['password_present'] ? 'present' : 'missing')
    );

    try {
        $resolution = $resolver->resolve($branch);
        $branchResults[$branch] = [
            'status' => 'PASS',
            'resolution' => $resolution,
        ];
        $add($branch . '_direct_sid_oracle_connect', true, 'Oracle identity verified');
    } catch (Throwable $error) {
        $branchResults[$branch] = [
            'status' => 'FAIL',
            'error' => $error->getMessage(),
        ];
        $add($branch . '_direct_sid_oracle_connect', false, $error->getMessage());
    }
}

$fingerprints = [];
$collision = false;
foreach ($branchResults as $branch => $result) {
    $fingerprint = (string)($result['resolution']['identity']['fingerprint'] ?? '');
    if ($fingerprint === '') {
        continue;
    }
    if (isset($fingerprints[$fingerprint])) {
        $collision = true;
    }
    $fingerprints[$fingerprint] = $branch;
}

$add(
    'distinct_oracle_identity_fingerprints',
    !$collision && count($fingerprints) === 3,
    count($fingerprints) . '/3 distinct fingerprints'
);

$failures = count(array_filter($checks, static function (array $check): bool {
    return $check['status'] === 'FAIL';
}));

$result = [
    'schema_version' => '1.0',
    'phase' => 'H11.0-P4.3',
    'policy' => 'STRICT_CONFIGURED_SID_DIRECT',
    'branches' => $branchResults,
    'diagnostics' => $resolver->diagnostics(),
    'checks' => $checks,
    'write_operations' => 'NONE',
    'failures' => $failures,
    'status' => $failures === 0 ? 'PASS' : 'FAIL',
];

header('Content-Type: application/json; charset=UTF-8');
echo json_encode(
    $result,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
