<?php
declare(strict_types=1);

use App\Core\Database\ConnectionFactory;
use App\Core\Support\Env;

$basePath = dirname(__DIR__);
$vendorAutoload = $basePath . '/vendor/autoload.php';

if (is_file($vendorAutoload)) {
    require $vendorAutoload;
} else {
    spl_autoload_register(static function (string $class) use ($basePath): void {
        $prefix = 'App\\';
        if (!str_starts_with($class, $prefix)) {
            return;
        }
        $relative = substr($class, strlen($prefix));
        $file = $basePath . '/src/' . str_replace('\\', '/', $relative) . '.php';
        if (is_file($file)) {
            require $file;
        }
    });
}

Env::load($basePath . '/.env');
/** @var array<string, mixed> $dbConfig */
$dbConfig = require $basePath . '/config/database.php';

$args = $argv;
array_shift($args);
$useRemote = in_array('--use-remote', $args, true);
$dryRun = in_array('--dry-run', $args, true);

if ($useRemote) {
    $remoteHost = (string) Env::get('DB_HOST_REMOTE', '');
    if ($remoteHost !== '') {
        $dbConfig['host'] = $remoteHost;
    }
}

$pdo = ConnectionFactory::make($dbConfig);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo 'Randomize order statuses' . PHP_EOL;
echo '[db-host] ' . (string) ($dbConfig['host'] ?? '') . PHP_EOL;
echo '[mode] ' . ($dryRun ? 'dry-run' : 'apply') . PHP_EOL;

$statusRows = $pdo->query('SELECT code FROM order_statuses WHERE is_active = 1 ORDER BY sort_order ASC, id ASC')->fetchAll(PDO::FETCH_COLUMN);
if (!is_array($statusRows) || $statusRows === []) {
    fwrite(STDERR, '[error] Brak aktywnych statusow w tabeli order_statuses.' . PHP_EOL);
    exit(1);
}

$statuses = [];
foreach ($statusRows as $row) {
    $code = strtolower(trim((string) $row));
    if ($code === '' || in_array($code, $statuses, true)) {
        continue;
    }
    $statuses[] = $code;
}
if ($statuses === []) {
    fwrite(STDERR, '[error] Nie znaleziono poprawnych kodow statusow.' . PHP_EOL);
    exit(1);
}

$ordersRows = $pdo->query('SELECT id, external_status_id FROM orders ORDER BY id ASC')->fetchAll(PDO::FETCH_ASSOC);
if (!is_array($ordersRows) || $ordersRows === []) {
    echo '[result] Brak zamowien do aktualizacji.' . PHP_EOL;
    exit(0);
}

$preview = [];
$changes = 0;
$updateStmt = $pdo->prepare('UPDATE orders SET external_status_id = :status, is_canceled_by_buyer = :is_canceled_by_buyer, updated_at = NOW() WHERE id = :id');

if (!$dryRun) {
    $pdo->beginTransaction();
}

try {
    foreach ($ordersRows as $row) {
        $id = max(0, (int) ($row['id'] ?? 0));
        if ($id <= 0) {
            continue;
        }
        $old = strtolower(trim((string) ($row['external_status_id'] ?? '')));
        $new = $statuses[array_rand($statuses)];

        if (count($preview) < 8) {
            $preview[] = ['id' => $id, 'old' => $old, 'new' => $new];
        }

        if (!$dryRun) {
            $updateStmt->execute([
                'status' => $new,
                'is_canceled_by_buyer' => $new === 'cancelled' ? 1 : 0,
                'id' => $id,
            ]);
        }
        $changes++;
    }

    if (!$dryRun && $pdo->inTransaction()) {
        $pdo->commit();
    }
} catch (Throwable $exception) {
    if (!$dryRun && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    fwrite(STDERR, '[error] ' . $exception->getMessage() . PHP_EOL);
    exit(1);
}

echo '[statuses] ' . implode(', ', $statuses) . PHP_EOL;
echo '[updated_orders] ' . $changes . PHP_EOL;
echo '[preview]' . PHP_EOL;
foreach ($preview as $row) {
    echo '  #' . $row['id'] . ': ' . $row['old'] . ' -> ' . $row['new'] . PHP_EOL;
}
echo 'Done.' . PHP_EOL;

