<?php

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/agent_runtime_lib.php';
require_once dirname(__DIR__) . '/app_access.php';

$conn = ensure_db(true);
$instanceId = 'runtime_test_' . bin2hex(random_bytes(4));
$key = 'RUNTIME-' . strtoupper(bin2hex(random_bytes(4)));
$conn->begin_transaction();
try {
  $saved = ua_agent_repo_save($conn, [
    'code'=>$key,
    'full_name'=>'Agent Install Runtime Test',
    'username'=>strtolower($key),
    'linked_instance_id'=>$instanceId,
    'is_active'=>1,
    'portal_enabled'=>1,
    'pos_enabled'=>1,
  ]);
  if (!$saved['ok']) throw new RuntimeException($saved['error']);

  $GLOBALS['UA_INSTALL_CONFIG_OVERRIDE'] = [
    'install_type'=>'agent',
    'server_url'=>'http://127.0.0.1:8080/',
    'database'=>ua_install_database_config(),
    'link'=>[
      'status'=>'approved',
      'instance_id'=>$instanceId,
      'secret'=>'runtime-test-secret',
      'server_url'=>'http://127.0.0.1:8080/',
    ],
  ];
  $resolved = ua_agent_portal_resolve_id($conn, 0);
  if ($resolved !== (int)$saved['id']) throw new RuntimeException('Linked agent was not resolved.');
  if (ua_install_home_page() !== 'agent_portal.php') throw new RuntimeException('Agent home page is not the portal.');
  if (!ua_install_page_allowed('agent_portal.php') || ua_install_page_allowed('dashboard.php')) {
    throw new RuntimeException('Agent installation access rules are invalid.');
  }

  $conn->rollback();
  echo json_encode([
    'ok'=>true,
    'install_type'=>'agent',
    'home_page'=>'agent_portal.php',
    'resolved_agent_id'=>$resolved,
    'dashboard_blocked'=>true,
    'portal_allowed'=>true,
    'rows_after_rollback'=>0,
  ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $e) {
  @$conn->rollback();
  fwrite(STDERR, $e->getMessage() . PHP_EOL);
  exit(1);
}
