<?php

require dirname(__DIR__) . '/agent_portal_lib.php';
require dirname(__DIR__) . '/agent_edit_request_lib.php';

$conn = ensure_db(true);
$suffix = bin2hex(random_bytes(5));
$agentCode = 'EDIT-ACCESS-' . strtoupper($suffix);
$agentId = 0;
$requestId = 0;
$exitCode = 0;

try {
  $saved = ua_agent_repo_save($conn, [
    'code'=>$agentCode,
    'full_name'=>'Agent Edit Access Flow Test',
    'username'=>strtolower($agentCode),
    'password'=>'edit-access-test-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'];

  $created = ua_agent_edit_access_request_create($conn, $agentId, 'Automated access flow test');
  if (empty($created['ok']) || !empty($created['granted'])) {
    throw new RuntimeException('The edit access request did not start in the pending state.');
  }
  $requestId = (int)$created['id'];
  $token = (string)$created['token'];
  $pending = ua_agent_edit_request_find($conn, $token, $agentId, 0);
  if (!$pending || (string)$pending['request_scope'] !== 'PORTAL_EDIT' || (string)$pending['status'] !== 'PENDING') {
    throw new RuntimeException('The portal edit request scope or pending state is invalid.');
  }

  $decision = ua_agent_edit_request_decide($conn, $requestId, 'APPROVED', 1);
  if (empty($decision['ok'])) throw new RuntimeException((string)($decision['error'] ?? 'Approval failed.'));
  if (!ua_agent_edit_request_is_granted($conn, $token, $agentId, 123456)) {
    throw new RuntimeException('The approved portal permission did not grant subscriber edit access.');
  }

  echo "agent_edit_access_flow_test: OK\n";
} catch (Throwable $e) {
  fwrite(STDERR, $e->getMessage() . PHP_EOL);
  $exitCode = 1;
} finally {
  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 agents WHERE id={$agentId}");
  }
  $left = @$conn->query("SELECT COUNT(*) c FROM agents WHERE code='" . $conn->real_escape_string($agentCode) . "'");
  if (!$left || (int)$left->fetch_assoc()['c'] !== 0) {
    fwrite(STDERR, "Edit access flow test cleanup failed.\n");
    $exitCode = 1;
  }
}

exit($exitCode);
