<?php

require_once __DIR__ . '/agent_schema.php';
require_once __DIR__ . '/agent_activity_lib.php';

if (!function_exists('ua_agent_sync_enqueue')) {
  function ua_agent_sync_enqueue(mysqli $conn, array $data): array {
    ua_agent_schema_migrate($conn);
    $key = substr(trim((string)($data['idempotency_key'] ?? '')), 0, 191);
    $instanceId = substr(trim((string)($data['instance_id'] ?? '')), 0, 80);
    if ($key === '' || $instanceId === '') return ['ok'=>false,'error'=>'معرف النسخة ومفتاح منع التكرار مطلوبان.'];
    $escaped = $conn->real_escape_string($key);
    $old = @$conn->query("SELECT * FROM agent_sync_events WHERE idempotency_key='{$escaped}' LIMIT 1");
    if ($old && $old->num_rows) return ['ok'=>true,'duplicate'=>true,'event'=>$old->fetch_assoc(),'error'=>''];

    $uuid = trim((string)($data['event_uuid'] ?? '')) ?: ua_agent_uuid();
    $agentId = (int)($data['agent_id'] ?? 0) ?: null;
    $direction = strtoupper(trim((string)($data['direction'] ?? 'OUTBOUND')));
    if (!in_array($direction, ['INBOUND','OUTBOUND'], true)) $direction = 'OUTBOUND';
    $eventType = substr(trim((string)($data['event_type'] ?? 'EVENT')), 0, 60);
    $entityType = substr(trim((string)($data['entity_type'] ?? '')), 0, 50);
    $entityId = substr(trim((string)($data['entity_id'] ?? '')), 0, 120);
    $payload = ua_agent_json($data['payload'] ?? []);
    $availableAt = (string)($data['available_at'] ?? date('Y-m-d H:i:s'));
    $stmt = $conn->prepare("INSERT INTO agent_sync_events (event_uuid,agent_id,instance_id,direction,event_type,entity_type,entity_id,idempotency_key,payload_json,status,available_at) VALUES (?,?,?,?,?,?,?,?,?,'PENDING',?)");
    if (!$stmt) return ['ok'=>false,'error'=>$conn->error];
    $stmt->bind_param('sissssssss', $uuid,$agentId,$instanceId,$direction,$eventType,$entityType,$entityId,$key,$payload,$availableAt);
    $ok = $stmt->execute();
    $id = $ok ? (int)$stmt->insert_id : 0;
    $error = $ok ? '' : $stmt->error;
    $stmt->close();
    return ['ok'=>$ok,'duplicate'=>false,'event'=>['id'=>$id,'event_uuid'=>$uuid],'error'=>$error];
  }
}

if (!function_exists('ua_agent_sync_mark')) {
  function ua_agent_sync_mark(mysqli $conn, int $eventId, string $status, array $result = [], string $error = ''): bool {
    $status = strtoupper($status);
    if (!in_array($status, ['PENDING','PROCESSING','DONE','FAILED','DEAD'], true)) return false;
    $resultJson = ua_agent_json($result);
    $stmt = $conn->prepare("UPDATE agent_sync_events SET status=?,result_json=?,last_error=?,attempts=attempts+1,
      available_at=CASE WHEN ?='FAILED' THEN DATE_ADD(NOW(), INTERVAL LEAST(60, POW(2, LEAST(attempts,5))) MINUTE) ELSE available_at END,
      processed_at=CASE WHEN ?='DONE' THEN NOW() ELSE processed_at END,updated_at=NOW() WHERE id=?");
    if (!$stmt) return false;
    $stmt->bind_param('sssssi', $status,$resultJson,$error,$status,$status,$eventId);
    $ok = $stmt->execute();
    $stmt->close();
    return (bool)$ok;
  }
}

if (!function_exists('ua_agent_sync_retry')) {
  function ua_agent_sync_retry(mysqli $conn, int $eventId): bool {
    $eventId = (int)$eventId;
    if ($eventId <= 0) return false;
    return (bool)@$conn->query("UPDATE agent_sync_events SET status='PENDING',available_at=NOW(),last_error=NULL,updated_at=NOW() WHERE id={$eventId} AND status IN ('FAILED','DEAD')");
  }
}
