import Foundation
import Testing
@testable import MacSyncShared

@Suite("ActivityLog")
struct ActivityLogTests {

    @MainActor
    @Test func newLogHasEmptyEntries() {
        let log = ActivityLog.shared
        log.clear()
        #expect(log.entries.isEmpty)
    }

    @MainActor
    @Test func logInsertsAtFront() {
        let log = ActivityLog.shared
        log.clear()
        log.info("First")
        log.info("Second")
        #expect(log.entries[0].message == "Second")
        #expect(log.entries[1].message == "First")
    }

    @MainActor
    @Test func entriesCappedAt50() {
        let log = ActivityLog.shared
        log.clear()
        for i in 0..<55 {
            log.info("Entry \(i)")
        }
        #expect(log.entries.count == 50)
    }

    @MainActor
    @Test func fiftyFirstEntryEvictsOldest() {
        let log = ActivityLog.shared
        log.clear()
        for i in 0..<51 {
            log.info("Entry \(i)")
        }
        #expect(log.entries.count == 50)
        #expect(log.entries[0].message == "Entry 50")
        #expect(log.entries[49].message == "Entry 1")
    }

    @MainActor
    @Test func clearRemovesAll() {
        let log = ActivityLog.shared
        log.info("Test")
        log.clear()
        #expect(log.entries.isEmpty)
    }

    @MainActor
    @Test func levelsSetCorrectly() {
        let log = ActivityLog.shared
        log.clear()
        log.info("info msg")
        log.success("success msg")
        log.warning("warning msg")
        log.error("error msg")
        #expect(log.entries[0].level == .error)
        #expect(log.entries[1].level == .warning)
        #expect(log.entries[2].level == .success)
        #expect(log.entries[3].level == .info)
    }

    @MainActor
    @Test func entriesHaveTimestampsCloseToNow() {
        let log = ActivityLog.shared
        log.clear()
        let before = Date()
        log.info("timed entry")
        let after = Date()
        let entry = log.entries[0]
        #expect(entry.timestamp >= before)
        #expect(entry.timestamp <= after)
    }
}
