<?php
declare(strict_types=1);

// Read-only constraint metadata from the isolated Store DM instance.
set_exception_handler(static function (Throwable $error): void {
    fwrite(STDERR, 'FK_METADATA_CHECK_FAILED ' . get_class($error)
        . ' code=' . (string)$error->getCode() . PHP_EOL);
    exit(2);
});
if ((string)getenv('POC_PORT') !== '5237'
    || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP') {
    throw new RuntimeException('Expected isolated Store DM target');
}
foreach (['POC_HOST', 'POC_USER', 'POC_PASSWORD'] as $key) {
    if ((string)getenv($key) === '') {
        throw new RuntimeException('Isolated Store connection unavailable');
    }
}
$pdo = new PDO(
    sprintf('dm:host=%s;port=5237;schema=ZHCT_APP', (string)getenv('POC_HOST')),
    (string)getenv('POC_USER'), (string)getenv('POC_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_UPPER]
);
$schema = strtoupper((string)$pdo->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
    ->fetchColumn());
if ($schema !== 'ZHCT_APP') {
    throw new RuntimeException('Unexpected current schema');
}
$rows = $pdo->query(
    "SELECT p.TABLE_NAME,COUNT(DISTINCT c.OWNER || ':' || c.CONSTRAINT_NAME) N"
    . ' FROM ALL_CONSTRAINTS c JOIN ALL_CONSTRAINTS p'
    . ' ON c.R_OWNER=p.OWNER AND c.R_CONSTRAINT_NAME=p.CONSTRAINT_NAME'
    . " WHERE c.CONSTRAINT_TYPE='R' AND p.OWNER='ZHCT_APP'"
    . " AND p.TABLE_NAME IN ('YDY_MEMBER_WEIGHT','YDY_NUTRITION_CUPBOARD',"
    . "'YDY_USER_DATA','YDY_STAFF_DEPARTMENT')"
    . ' GROUP BY p.TABLE_NAME ORDER BY p.TABLE_NAME'
)->fetchAll(PDO::FETCH_ASSOC);
$counts = array_fill_keys(['YDY_MEMBER_WEIGHT', 'YDY_NUTRITION_CUPBOARD',
    'YDY_USER_DATA', 'YDY_STAFF_DEPARTMENT'], 0);
foreach ($rows as $row) {
    $counts[$row['TABLE_NAME']] = (int)$row['N'];
}
echo json_encode(['target' => 'store-nonproduction-dm', 'visible_incoming_fk_counts' => $counts],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
