// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Thibault Ducray
//
// This file is part of MyPwdTool's open-source sync/encryption core — see
// LICENSE-SYNC-CRYPTO.md at the repo root and https://tducray.fr/mypwdtool/open-source/.
// The rest of this application is proprietary and NOT covered by this license.

import Foundation

// MARK: - SyncOutbox

/// Simple in-memory outbox for pending sync changes.
/// Thread-safe via NSLock.
final class SyncOutbox {

    static let shared = SyncOutbox()

    struct Item: Identifiable {
        let id = UUID()
        let op: SyncOp
        let entryId: UUID
        let updatedAt: Date
        let entry: Entry?       // nil for delete
    }

    private var items: [Item] = []
    private let lock = NSLock()

    private init() {}

    /// Enqueue an item for sending.
    func enqueue(_ item: Item) {
        lock.lock()
        defer { lock.unlock() }
        items.append(item)
    }

    /// Returns and clears all pending items atomically.
    func drain() -> [Item] {
        lock.lock()
        defer { lock.unlock() }
        let result = items
        items = []
        return result
    }

    /// True if there are no pending items.
    var isEmpty: Bool {
        lock.lock()
        defer { lock.unlock() }
        return items.isEmpty
    }
}
