import XCTest

final class OverviewCreateMutatingUITests: ForgejoUITestBase {

    // MARK: - Create Issue from Issues Overview (mutates, creates an issue)

    @MainActor
    func testCreateIssueFromOverview() throws {
        loginAndWaitForHome()
        app.tabBars.buttons["Issues"].tap()

        // Wait for the issues list to load
        XCTAssertTrue(app.cells.firstMatch.waitForExistence(timeout: 10), "Issues should load")

        // Tap floating create button
        let createButton = app.buttons["issue-create-button"]
        XCTAssertTrue(createButton.waitForExistence(timeout: 10), "Floating create button should exist on Issues overview")
        createButton.tap()

        // Repository picker sheet should appear
        XCTAssertTrue(app.staticTexts["Select Repository"].waitForExistence(timeout: 10), "Repository picker should appear")

        // Select test-repo via accessibility identifier on the button
        let repoButton = app.buttons["repo-picker-testadmin/test-repo"]
        XCTAssertTrue(repoButton.waitForExistence(timeout: 10), "test-repo should appear in the picker")
        repoButton.tap()

        // Issue create form should appear after selecting a repo
        XCTAssertTrue(app.staticTexts["New Issue"].waitForExistence(timeout: 15), "Issue create form should appear after selecting a repo")

        // Fill in the title
        let titleField = app.textFields["issue-create-title-field"]
        XCTAssertTrue(titleField.waitForExistence(timeout: 5))
        titleField.tap()
        titleField.typeText("Issue created from overview")

        // Submit
        let submitButton = app.buttons["issue-create-submit"]
        XCTAssertTrue(submitButton.waitForExistence(timeout: 5))
        submitButton.tap()

        // After creation, the sheet dismisses and the issues list should refresh
        // showing the newly created issue
        XCTAssertTrue(
            app.staticTexts["Issue created from overview"].waitForExistence(timeout: 15),
            "Newly created issue should appear in the overview list"
        )
    }
}
