<?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);

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 'Fill order item images' . PHP_EOL;
echo '[db-host] ' . (string) ($dbConfig['host'] ?? '') . PHP_EOL;

$rows = $pdo->query('SELECT id FROM order_items WHERE media_url IS NULL OR media_url = ""')->fetchAll(PDO::FETCH_ASSOC);
if (!is_array($rows) || $rows === []) {
    echo '[result] nothing to update' . PHP_EOL;
    exit(0);
}

$update = $pdo->prepare('UPDATE order_items SET media_url = :media_url, updated_at = NOW() WHERE id = :id');
$updated = 0;

$pdo->beginTransaction();
try {
    foreach ($rows as $row) {
        $id = max(0, (int) ($row['id'] ?? 0));
        if ($id <= 0) {
            continue;
        }

        $update->execute([
            'media_url' => 'https://picsum.photos/seed/order-item-' . $id . '/120/120',
            'id' => $id,
        ]);
        $updated++;
    }
    $pdo->commit();
} catch (Throwable $exception) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    fwrite(STDERR, '[error] ' . $exception->getMessage() . PHP_EOL);
    exit(1);
}

echo '[updated] ' . $updated . PHP_EOL;
echo 'Done.' . PHP_EOL;

