<?php
/**
 * Runs products:backfill-media — migrates existing product_images (legacy
 * table, populated by the CSV import + products:download-images) into
 * Spatie Media Library collections ('featured_image' / 'gallery'), which
 * is what the admin's Thumbnail/Gallery dropzones actually read from.
 *
 * Usage: upload to public/run-backfill-media.php, visit once, then
 * DELETE this file.
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '1024M');
set_time_limit(0);

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

echo "<pre>";

try {
    if (class_exists(\Laravel\Telescope\Telescope::class)) {
        \Laravel\Telescope\Telescope::stopRecording();
    }
    Illuminate\Support\Facades\DB::connection()->disableQueryLog();

    echo "Starting products:backfill-media ...\n\n";

    $exitCode = Illuminate\Support\Facades\Artisan::call('products:backfill-media');
    echo Illuminate\Support\Facades\Artisan::output();

    echo "\nExit code: {$exitCode}\n";
    echo $exitCode === 0 ? "\nDONE.\n" : "\nFinished with a non-zero exit code — check the output above.\n";
    echo "\nDelete public/run-backfill-media.php now that it's done.\n";
} catch (\Throwable $e) {
    echo "FATAL ERROR:\n" . $e->getMessage() . "\n\n" . $e->getTraceAsString();
    echo "\n\nIf this looks like a timeout (page just stops, no error text), let me know — ";
    echo "the command may need to be run in smaller batches, and I'll need to see its source to build that.\n";
}

echo "</pre>";
