<?php
declare(strict_types=1);

$host=getenv('MYSQL_TEST_HOST')?:'127.0.0.1';$user=getenv('MYSQL_TEST_USER')?:'root';$pass=getenv('MYSQL_TEST_PASS')?:'';
$database='tmp_mobile_'.date('Ymd_His').'_'.bin2hex(random_bytes(3));
if(!preg_match('/^tmp_mobile_[0-9_]+_[a-f0-9]{6}$/',$database))throw new RuntimeException('Nome temporário inseguro.');
$db=new mysqli($host,$user,$pass);$db->set_charset('utf8mb4');
function runSql(mysqli $db,string $sql):void{if(!$db->multi_query($sql))throw new RuntimeException($db->error);do{if($result=$db->store_result())$result->free();if(!$db->more_results())break;}while($db->next_result());if($db->errno)throw new RuntimeException($db->error);}
try{
 if(!$db->query("CREATE DATABASE `{$database}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"))throw new RuntimeException($db->error);$db->select_db($database);
 $sql=file_get_contents(dirname(__DIR__).'/SQL_INVENTARIO_MOBILE.sql');if($sql===false)throw new RuntimeException('SQL ausente.');runSql($db,$sql);runSql($db,$sql);
 $required=['ti_mobile_config','ti_mobile_dispositivos','ti_mobile_sincronizacoes','ti_mobile_eventos','ti_mobile_apps','ti_mobile_apps_catalogo','ti_mobile_nonces','ti_mobile_rate_limits','ti_mobile_auditoria'];
 $result=$db->query('SHOW TABLES');$tables=[];while($row=$result->fetch_row())$tables[]=$row[0];foreach($required as $table)if(!in_array($table,$tables,true))throw new RuntimeException('Tabela não criada: '.$table);
 $row=$db->query('SELECT sync_interval_min,recent_hours,silent_hours,offline_alert_hours,current_app_version_code FROM ti_mobile_config WHERE id=1')->fetch_assoc();if(!$row||(int)$row['sync_interval_min']!==30||(int)$row['recent_hours']!==2||(int)$row['silent_hours']!==24||(int)$row['offline_alert_hours']!==168)throw new RuntimeException('Configuração inicial inválida.');
 $apps=(int)$db->query('SELECT COUNT(*) total FROM ti_mobile_apps_catalogo')->fetch_assoc()['total'];if($apps<5)throw new RuntimeException('Catálogo inicial incompleto.');
 echo "SQL TEST OK\nBanco criado duas vezes sem perda; {$apps} apps iniciais; ".count($required)." tabelas validadas.\n";
}finally{$db->select_db('mysql');if(str_starts_with($database,'tmp_mobile_'))$db->query("DROP DATABASE IF EXISTS `{$database}`");$db->close();}
?>
