<?php
declare(strict_types=1);

require __DIR__ . '/../../config/bootstrap.php';
use App\Core\Database;

$db = Database::getInstance();

function table_exists($db,string $t):bool{
  $st=$db->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
  $st->execute([':t'=>$t]);
  return (int)$st->fetchColumn()>0;
}
function col_exists($db,string $t,string $c):bool{
  $st=$db->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
  $st->execute([':t'=>$t,':c'=>$c]);
  return (int)$st->fetchColumn()>0;
}
function add_org($db,string $t):void{
  if(!table_exists($db,$t)){ echo "SKIP missing $t\n"; return; }
  if(!col_exists($db,$t,'org_id')){
    $db->exec("ALTER TABLE {$t} ADD COLUMN org_id BIGINT UNSIGNED NULL");
    $db->exec("ALTER TABLE {$t} ADD KEY idx_org_id (org_id)");
    echo "Added {$t}.org_id\n";
  } else {
    echo "{$t}.org_id exists\n";
  }
}

$defaultOrg=(int)$db->query("SELECT id FROM organizations ORDER BY id ASC LIMIT 1")->fetchColumn();
if($defaultOrg<=0) $defaultOrg=1;

echo "Pack204.6 jobs isolation (defaultOrg={$defaultOrg})\n";

// Common job tables (we add org_id only if table exists)
$tables=['jobs','job_queue','jobs_queue','job_runs','jobs_runs','background_jobs','cron_jobs'];
foreach($tables as $t) add_org($db,$t);

// Backfill
foreach($tables as $t){
  if(table_exists($db,$t) && col_exists($db,$t,'org_id')){
    $db->exec("UPDATE {$t} SET org_id={$defaultOrg} WHERE org_id IS NULL");
    echo "Backfilled {$t}.org_id\n";
  }
}

echo "Pack204.6 done\n";
