<?php

declare(strict_types=1);

/**
 * Sets artworks.updated_at = artworks.created_at for every row where they differ.
 *
 * Usage (local):
 *   php scripts/fix_artworks_updated_at.php [--dry-run]
 *
 * Usage (production via SSH):
 *   ssh klevze@server3.klevze.si "cd /opt/www/virtual/SkinbaseNova && php scripts/fix_artworks_updated_at.php"
 */

require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

$options  = getopt('', ['dry-run']);
$isDryRun = array_key_exists('dry-run', $options);

use Illuminate\Support\Facades\DB;

// Count rows that need updating
$total = DB::table('artworks')
    ->whereColumn('updated_at', '!=', 'created_at')
    ->orWhereNull('updated_at')
    ->count();

if ($total === 0) {
    fwrite(STDOUT, "Nothing to do: all artworks already have updated_at = created_at.\n");
    exit(0);
}

fwrite(STDOUT, sprintf("Rows to fix: %d%s\n", $total, $isDryRun ? ' (dry-run, no changes written)' : ''));

if ($isDryRun) {
    exit(0);
}

// Single bulk UPDATE — fast even on large tables, uses the existing index on created_at
$affected = DB::statement('UPDATE artworks SET updated_at = created_at WHERE updated_at != created_at OR updated_at IS NULL');

fwrite(STDOUT, sprintf("Done. updated_at synced to created_at for %d rows.\n", $total));
