<?php

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/agent_portal_lib.php';
require_once dirname(__DIR__) . '/install_link_lib.php';

$conn = ensure_db(true);
ua_agent_schema_migrate($conn);
ua_link_ensure_schema($conn);

$suffix = bin2hex(random_bytes(5));
$instanceId = 'portal_connection_' . $suffix;
$agentCode = 'PORTAL-' . strtoupper($suffix);
$agentId = 0;

try {
  $instanceName = 'Agent Portal Connection Test';
  $installType = 'agent';
  $status = 'approved';
  $secretHash = hash('sha256', 'portal-connection-secret-' . $suffix);
  $stmt = $conn->prepare(
    "INSERT INTO ua_link_requests
      (instance_id,instance_name,install_type,request_secret_hash,status,approved_at,last_seen_at,created_at,updated_at)
     VALUES (?,?,?,?,?,NOW(),DATE_SUB(NOW(), INTERVAL 1 DAY),NOW(),NOW())"
  );
  if (!$stmt) throw new RuntimeException($conn->error);
  $stmt->bind_param('sssss', $instanceId, $instanceName, $installType, $secretHash, $status);
  if (!$stmt->execute()) throw new RuntimeException($stmt->error);
  $stmt->close();

  $saved = ua_agent_repo_save($conn, [
    'code'=>$agentCode,
    'full_name'=>'Agent Portal Connection Test',
    'username'=>strtolower($agentCode),
    'linked_instance_id'=>$instanceId,
    'password'=>'portal-connection-password',
    'is_active'=>1,
    'portal_enabled'=>1,
    'pos_enabled'=>1,
  ]);
  if (empty($saved['ok'])) throw new RuntimeException((string)($saved['error'] ?? 'Agent creation failed.'));
  $agentId = (int)$saved['id'];
  $agent = ua_agent_repo_get($conn, $agentId);
  if (!$agent) throw new RuntimeException('Agent was not found after creation.');

  $before = agent_portal_connection_state($conn, $agent);
  if (!empty($before['connected'])) {
    throw new RuntimeException('A stale heartbeat was incorrectly reported as connected.');
  }

  agent_portal_touch_connection($conn, $agent);
  $after = agent_portal_connection_state($conn, $agent);
  if (empty($after['connected'])) {
    throw new RuntimeException('An authenticated portal heartbeat did not restore the connected state.');
  }

  $lastSeen = '';
  $stmt = $conn->prepare("SELECT last_seen_at FROM ua_link_requests WHERE instance_id=? LIMIT 1");
  $stmt->bind_param('s', $instanceId);
  $stmt->execute();
  $row = $stmt->get_result()->fetch_assoc();
  $stmt->close();
  $lastSeen = (string)($row['last_seen_at'] ?? '');
  if ($lastSeen === '' || strtotime($lastSeen) < (time() - 60)) {
    throw new RuntimeException('The authoritative portal heartbeat was not persisted.');
  }

  echo json_encode([
    'ok'=>true,
    'stale_state'=>'offline',
    'authenticated_state'=>'online',
    'heartbeat_persisted'=>true,
  ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $e) {
  fwrite(STDERR, $e->getMessage() . PHP_EOL);
  $exitCode = 1;
} finally {
  $instanceEsc = $conn->real_escape_string($instanceId);
  if ($agentId > 0) {
    @$conn->query("DELETE FROM agent_subscriber_edit_requests WHERE agent_id={$agentId}");
    @$conn->query("DELETE FROM agent_activity_log WHERE agent_id={$agentId}");
    @$conn->query("DELETE FROM agent_sync_events WHERE agent_id={$agentId}");
    @$conn->query("DELETE FROM agent_ledger_entries WHERE agent_id={$agentId}");
    @$conn->query("DELETE FROM agents WHERE id={$agentId}");
  }
  @$conn->query("DELETE FROM ua_link_requests WHERE instance_id='{$instanceEsc}'");

  $agentLeft = @$conn->query("SELECT COUNT(*) c FROM agents WHERE code='" . $conn->real_escape_string($agentCode) . "'");
  $linkLeft = @$conn->query("SELECT COUNT(*) c FROM ua_link_requests WHERE instance_id='{$instanceEsc}'");
  $leftCount = ($agentLeft ? (int)$agentLeft->fetch_assoc()['c'] : 1)
    + ($linkLeft ? (int)$linkLeft->fetch_assoc()['c'] : 1);
  if ($leftCount !== 0) {
    fwrite(STDERR, "Portal connection test cleanup left {$leftCount} rows.\n");
    $exitCode = 1;
  }
}

exit($exitCode ?? 0);
