<?php

require_once __DIR__ . '/_bootstrap.php';
$auth = agent_sync_authenticate($conn);
$events = $auth['payload']['events'] ?? [];
if (!is_array($events)) agent_sync_reply(422, ['ok'=>false,'error'=>'EVENTS_REQUIRED']);

$accepted = [];
foreach (array_slice($events, 0, 100) as $event) {
  if (!is_array($event)) continue;
  $eventUuid = trim((string)($event['event_uuid'] ?? ''));
  $eventType = substr(trim((string)($event['event_type'] ?? 'EVENT')), 0, 60);
  if ($eventUuid === '') continue;
  $queued = ua_agent_sync_enqueue($conn, [
    'event_uuid'=>$eventUuid,
    'agent_id'=>(int)$auth['agent']['id'],
    'instance_id'=>$auth['instance_id'],
    'direction'=>'INBOUND',
    'event_type'=>$eventType,
    'entity_type'=>(string)($event['entity_type'] ?? ''),
    'entity_id'=>(string)($event['entity_id'] ?? ''),
    'idempotency_key'=>'INBOUND:' . $auth['instance_id'] . ':' . $eventUuid,
    'payload'=>$event['payload'] ?? [],
  ]);
  if (!$queued['ok']) continue;
  $accepted[] = ['event_uuid'=>$eventUuid,'duplicate'=>!empty($queued['duplicate'])];
  ua_agent_activity_add($conn, [
    'event_uuid'=>$eventUuid,
    'agent_id'=>(int)$auth['agent']['id'],
    'event_type'=>$eventType,
    'direction'=>'TO_MAIN',
    'source_instance_id'=>$auth['instance_id'],
    'entity_type'=>(string)($event['entity_type'] ?? ''),
    'entity_id'=>(string)($event['entity_id'] ?? ''),
    'request_id'=>$eventUuid,
    'status'=>'SUCCESS',
    'summary'=>'تم استلام حدث من نسخة المعتمد.',
    'payload'=>$event['payload'] ?? [],
    'actor_type'=>'agent_instance',
    'actor_id'=>(int)$auth['agent']['id'],
  ]);
}
agent_sync_reply(200, ['ok'=>true,'accepted'=>$accepted]);
