import XCTest
@testable import CommandNotch

@MainActor
final class ScreenContextTests: XCTestCase {
    func testInteractiveResizeDefersPersistingSettingsUntilResizeEnds() {
        let store = ScreenContextTestSettingsStore()
        var settings = AppSettings.default
        settings.display.openWidth = 640
        settings.display.openHeight = 350
        store.storedSettings = settings

        let controller = AppSettingsController(store: store)
        let screen = ScreenContext(
            id: "screen-a",
            workspaceID: UUID(),
            settingsController: controller,
            screenProvider: { _ in nil }
        )

        screen.open()
        screen.beginInteractiveResize()
        screen.resizeOpenNotch(to: CGSize(width: 800, height: 420))

        XCTAssertEqual(screen.notchSize.width, 800)
        XCTAssertEqual(screen.notchSize.height, 420)
        XCTAssertEqual(controller.settings.display.openWidth, 640)
        XCTAssertEqual(controller.settings.display.openHeight, 350)

        screen.endInteractiveResize()

        XCTAssertEqual(controller.settings.display.openWidth, 800)
        XCTAssertEqual(controller.settings.display.openHeight, 420)
        XCTAssertEqual(store.storedSettings.display.openWidth, 800)
        XCTAssertEqual(store.storedSettings.display.openHeight, 420)
    }

    func testFocusLossAutoCloseSuppressionCanBeToggled() {
        let controller = AppSettingsController(store: ScreenContextTestSettingsStore())
        let screen = ScreenContext(
            id: "screen-a",
            workspaceID: UUID(),
            settingsController: controller,
            screenProvider: { _ in nil }
        )

        XCTAssertFalse(screen.suppressCloseOnFocusLoss)

        screen.setCloseOnFocusLossSuppressed(true)
        XCTAssertTrue(screen.suppressCloseOnFocusLoss)

        screen.setCloseOnFocusLossSuppressed(false)
        XCTAssertFalse(screen.suppressCloseOnFocusLoss)
    }
}

private final class ScreenContextTestSettingsStore: AppSettingsStoreType {
    var storedSettings = AppSettings.default

    func load() -> AppSettings {
        storedSettings
    }

    func save(_ settings: AppSettings) {
        storedSettings = settings
    }
}
