<?php

declare(strict_types=1);

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

use App\Core\BranchReadiness;
use App\Services\BranchOracleAccessResolver;

$resolver = new BranchOracleAccessResolver();
$branches = BranchReadiness::liveCodes();
$results = [];
$failed = [];

foreach ($branches as $branch) {
    try {
        $rows = $resolver->fetchAll(
            $branch,
            static function (string $suffix): string {
                return "
                    SELECT table_name, column_name
                    FROM all_tab_columns
                    WHERE owner = UPPER(:owner_name)
                      AND table_name IN ('RCP_VISIT', 'RCP_SERVICE_RESERVATION')
                      AND column_name IN ('OUTPTA_EMERGENCY_TYPE', 'CLINIC_ID')
                    ORDER BY table_name, column_name
                ";
            },
            [
                'owner_name' => (string)config('hospitals.' . $branch . '.database.schema', 'WATANY'),
            ]
        );

        $results[$branch] = [
            'status' => 'PASS',
            'columns' => $rows,
        ];
    } catch (\Throwable $error) {
        $message = preg_replace('/\s+/', ' ', $error->getMessage()) ?? $error->getMessage();
        $code = 'ORACLE_SOURCE_UNAVAILABLE';
        if (preg_match('/ORA-\d{5}/i', $message, $matches) === 1) {
            $code = strtoupper((string)$matches[0]);
        }
        $results[$branch] = [
            'status' => 'FAIL',
            'error_code' => $code,
            'error' => trim($message),
        ];
        $failed[] = $branch;
    }
}

$output = [
    'schema' => 'BRANCH_COMPARISON_EMERGENCY_COLUMN_DIAGNOSTIC_V1',
    'captured_at' => date(DATE_ATOM),
    'branches' => $branches,
    'results' => $results,
    'status' => $failed === [] ? 'PASS' : 'FAIL',
    'failed_branches' => $failed,
    'oracle_writes' => 'NONE',
];

echo json_encode($output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($failed === [] ? 0 : 1);
