import XCTest
@testable import PortfolioJournal

final class BackupServiceTests: XCTestCase {
    private var tempRoot: URL!

    override func setUp() {
        super.setUp()
        tempRoot = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString, isDirectory: true)
        try? FileManager.default.createDirectory(at: tempRoot, withIntermediateDirectories: true)
    }

    override func tearDown() {
        if let tempRoot {
            try? FileManager.default.removeItem(at: tempRoot)
        }
        super.tearDown()
    }

    func testCreateBackupPrunesToRetentionCount() {
        let localBase = tempRoot.appendingPathComponent("Local", isDirectory: true)
        try? FileManager.default.createDirectory(at: localBase, withIntermediateDirectories: true)

        var dates = [
            Date(timeIntervalSince1970: 100),
            Date(timeIntervalSince1970: 200)
        ]

        let service = BackupService(
            fileManager: .default,
            dateProvider: { dates.removeFirst() },
            localBaseDirectoryProvider: { localBase },
            iCloudBaseDirectoryProvider: { nil },
            exportProvider: { "{}" }
        )

        _ = service.createBackup(retentionCount: 1, includeICloud: false)
        let records = service.createBackup(retentionCount: 1, includeICloud: false)

        XCTAssertEqual(records.count, 1)
        XCTAssertEqual(records.first?.location, .local)
    }

    func testCreateBackupIncludesICloudWhenEnabled() {
        let localBase = tempRoot.appendingPathComponent("Local", isDirectory: true)
        let iCloudBase = tempRoot.appendingPathComponent("iCloud", isDirectory: true)
        try? FileManager.default.createDirectory(at: localBase, withIntermediateDirectories: true)
        try? FileManager.default.createDirectory(at: iCloudBase, withIntermediateDirectories: true)

        let service = BackupService(
            fileManager: .default,
            dateProvider: { Date(timeIntervalSince1970: 300) },
            localBaseDirectoryProvider: { localBase },
            iCloudBaseDirectoryProvider: { iCloudBase },
            exportProvider: { "{}" }
        )

        let records = service.createBackup(retentionCount: 5, includeICloud: true)
        let locations = Set(records.map { $0.location })

        XCTAssertTrue(locations.contains(.local))
        XCTAssertTrue(locations.contains(.iCloud))
    }
}
