<?php

declare(strict_types=1);

$dialect = getenv('POC_DIALECT');
$marker = (string)getenv('POC_MARKER');
if (!in_array($dialect, ['mysql', 'dm'], true)
    || !preg_match('/^CDXPAY[A-F0-9]{8}$/', $marker)) exit(2);
$connect = static function (bool $ai) use ($dialect): PDO {
    $prefix = $ai ? 'POC_AI_' : 'POC_';
    $host = getenv($prefix . 'HOST');
    $port = getenv($prefix . 'PORT');
    $schema = getenv($prefix . 'SCHEMA');
    $dsn = $dialect === 'dm'
        ? "dm:host=$host;port=$port;schema=$schema"
        : "mysql:host=$host;port=$port;dbname=$schema;charset=utf8mb4";
    return new PDO($dsn, getenv($prefix . 'USER'), getenv($prefix . 'PASSWORD'),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
};
$store = $connect(false);
$ai = $connect(true);
$s = static function (string $name) use ($dialect): string {
    return $dialect === 'dm' ? 'YDY_' . strtoupper($name) : 'ydy_' . strtolower($name);
};
$a = static function (string $name) use ($dialect): string {
    return $dialect === 'dm' ? 'YOSHOP_' . strtoupper($name) : 'yoshop_' . strtolower($name);
};
$count = static function (PDO $pdo, string $table, string $column, string $value): int {
    $query = $pdo->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $column . '=?');
    $query->execute([$value]);
    return (int)$query->fetchColumn();
};
$rows = [
    'store_orders' => $count($store, $s('meal_order'), 'MSGID', $marker),
    'store_users' => $count($store, $s('user'), 'ACCOUNT', $marker),
    'store_staff' => $count($store, $s('staff'), 'NAME', $marker),
    'store_auth' => $count($store, $s('api_auth'), 'ACCOUNT', $marker),
    'ai_users' => $count($ai, $a('user'), 'NICK_NAME', $marker),
];
if (array_sum($rows) !== 0) throw new RuntimeException('Commit fault fixture cleanup left rows');
echo json_encode(['dialect' => $dialect, 'marker' => $marker,
    'cleanup_verified' => true, 'counts' => $rows]) . PHP_EOL;
