<?php
declare(strict_types=1);
namespace Machweis\Backend;
use PDO;
final readonly class SyncChangeRecorder
{
/** @var array<string, string> */
private const TYPES = [
'customers' => 'customers',
'sites' => 'sites',
'jobs' => 'jobs',
'employee_profiles' => 'employee_profiles',
'job_assignments' => 'job_assignments',
];
public function __construct(private PDO $pdo) {}
/** @param array<string, mixed> $row */
public function recordRow(string $table, array $row): int
{
$entityType = self::TYPES[$table] ?? throw new \InvalidArgumentException('Unsupported sync entity.');
$operation = ($row['deleted_at'] ?? null) === null ? 'upsert' : 'delete';
$statement = $this->pdo->prepare('INSERT INTO sync_changes (tenant_id, entity_type, entity_id, operation, row_version, data_json, changed_at) VALUES (?, ?, ?, ?, ?, ?, UTC_TIMESTAMP())');
$statement->execute([(string) $row['tenant_id'], $entityType, (string) $row['id'], $operation, (int) $row['row_version'], json_encode($row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
return (int) $this->pdo->lastInsertId();
}
/** @return array<string, mixed> */
public function current(string $table, string $tenant, string $id): array
{
if (!isset(self::TYPES[$table])) throw new \InvalidArgumentException('Unsupported sync entity.');
$statement = $this->pdo->prepare("SELECT * FROM $table WHERE id = ? AND tenant_id = ?");
$statement->execute([$id, $tenant]);
$row = $statement->fetch();
if (!is_array($row)) throw new \InvalidArgumentException('Sync entity not found.');
return $row;
}
public function recordCurrent(string $table, string $tenant, string $id): int
{
return $this->recordRow($table, $this->current($table, $tenant, $id));
}
}
