import Foundation

// MARK: - Transaction Queue

/// Serializes list view updates to prevent concurrent modification.
/// Telegram equivalent: `ListViewTransactionQueue` (ListViewTransactionQueue.swift:1-67).
///
/// Pattern: FIFO queue. Next transaction starts only after previous completes.
/// Prevents UI glitches from overlapping snapshot + layout operations.
final class RosettaTransactionQueue {

    typealias Transaction = (@escaping () -> Void) -> Void

    private var pending: [Transaction] = []
    private var isExecuting = false

    /// Enqueue a transaction. If queue is idle, executes immediately.
    /// Transaction MUST call the completion closure when done.
    func enqueue(_ transaction: @escaping Transaction) {
        pending.append(transaction)
        if !isExecuting {
            executeNext()
        }
    }

    private func executeNext() {
        guard !pending.isEmpty else {
            isExecuting = false
            return
        }
        isExecuting = true
        let transaction = pending.removeFirst()
        transaction { [weak self] in
            self?.executeNext()
        }
    }

    /// Cancel all pending transactions (e.g., when view is deallocated).
    func cancelAll() {
        pending.removeAll()
        isExecuting = false
    }
}
