using HikvisionAttendanceManager.App.Models; namespace HikvisionAttendanceManager.App.Services; public sealed class DepartmentalUserSyncService( UserSyncEngine engine, OperationHistoryService history) { public async Task<(SyncHistoryEntry Entry, IReadOnlyList Results)> SyncAsync( Device device, IEnumerable employees, string contextSummary, IProgress? progress, CancellationToken cancellationToken) { var list = employees.ToList(); AppLogger.TraceEnter("USER_SYNC", nameof(SyncAsync), $"device={device.IpAddress} count={list.Count} context={contextSummary}"); var entry = new SyncHistoryEntry { Operation = SyncOperationKind.DepartmentalUserSync, TargetDevice = device.DisplayName, Context = contextSummary, Total = list.Count, Status = "Running" }; await history.AddAsync(entry, cancellationToken); var results = await engine.RunAsync(device, list, initialEnrollment: true, progress, cancellationToken); entry.CompletedAt = DateTime.Now; entry.Success = results.Count(r => r.OverallResult is "SUCCESS" or "ALREADY_EXISTS"); entry.Failed = results.Count(r => r.OverallResult is "FAILED" or "PARTIAL"); entry.Skipped = results.Count(r => r.OverallResult == "SKIPPED"); entry.Status = entry.Failed > 0 ? "Completed with errors" : "Completed"; await history.UpdateAsync(entry, cancellationToken); AppLogger.TraceExit("USER_SYNC", nameof(SyncAsync), $"success={entry.Success} failed={entry.Failed} skipped={entry.Skipped}"); return (entry, results); } }