#!/usr/bin/env php
<?php



declare(strict_types=1);

if (php_sapi_name() !== 'cli') {
    echo "CLI only\n";
    exit(1);
}

require dirname(__DIR__) . '/config/php-guard.php';  
require dirname(__DIR__) . '/config/app.php';

$tmpDir = APP_ROOT . '/storage/tmp';
if (!is_dir($tmpDir)) {
    mkdir($tmpDir, 0755, true);
}

$pidFile = $tmpDir . '/bulk-delete-worker.pid';
file_put_contents($pidFile, (string) getmypid());

require_once APP_ROOT . '/src/Admin/VideoController.php';
require_once APP_ROOT . '/src/Front/SitemapController.php';  

try {
    Database::reconnect();
    error_log('BulkDelete: Worker started (PID ' . getmypid() . ')');

    $maxSeconds = 600;  
    $start = time();

    while ((time() - $start) < $maxSeconds) {
        $hasMore = AdminVideoController::processDeleteChunk();
        if (!$hasMore) {
            break;
        }
         
        usleep(200000);  
    }

    error_log('BulkDelete: Worker finished');
} finally {
    @unlink($pidFile);
}
