import XCTest

final class PermissionUITests: ForgejoUITestBase {

    override func setUpWithError() throws {
        try super.setUpWithError()

        // Override credentials to use the read-only user
        app = XCUIApplication()
        app.launchArguments += [
            "-dev_serverURL", serverURL,
            "-dev_username", "readonlyuser",
            "-dev_password", "readonly1234",
        ]
    }

    // MARK: - Issue Detail, read-only user

    @MainActor
    func testIssueDetailHidesActionsForReadOnlyUser() throws {
        loginAndWaitForHome()

        navigateToIssueTab()

        let issueCell = app.staticTexts["Test issue 1 from integration tests"].firstMatch
        XCTAssertTrue(issueCell.waitForExistence(timeout: 10))
        issueCell.tap()

        let title = app.staticTexts["issue-detail-title"]
        XCTAssertTrue(title.waitForExistence(timeout: 10))

        expandActionMenu()

        // Comment button should always be visible
        let commentButton = app.buttons["issue-comment-button"]
        XCTAssertTrue(commentButton.waitForExistence(timeout: 5), "Comment button should be visible for read-only user")

        // Edit and Close/Reopen should be hidden
        let editButton = app.buttons["issue-edit-button"]
        XCTAssertFalse(editButton.exists, "Edit button should be hidden for read-only user")

        let toggleStateButton = app.buttons["issue-toggle-state"]
        XCTAssertFalse(toggleStateButton.exists, "Close/Reopen button should be hidden for read-only user")
    }

    // MARK: - PR Detail, read-only user

    @MainActor
    func testPRDetailHidesActionsForReadOnlyUser() throws {
        loginAndWaitForHome()

        navigateToPRTab()

        let prCell = app.staticTexts["Add feature file"].firstMatch
        XCTAssertTrue(prCell.waitForExistence(timeout: 10))
        prCell.tap()

        let title = app.staticTexts["pr-detail-title"]
        XCTAssertTrue(title.waitForExistence(timeout: 10))

        expandActionMenu()

        // Comment and Review should always be visible
        let commentButton = app.buttons["pr-comment-button"]
        XCTAssertTrue(commentButton.waitForExistence(timeout: 5), "Comment button should be visible for read-only user")

        let reviewButton = app.buttons["pr-submit-review"]
        XCTAssertTrue(reviewButton.exists, "Review button should be visible for read-only user")

        // Edit, Merge, Close/Reopen should be hidden
        let editButton = app.buttons["pr-edit-button"]
        XCTAssertFalse(editButton.exists, "Edit button should be hidden for read-only user")

        let mergeButton = app.buttons["pr-merge-button"]
        XCTAssertFalse(mergeButton.exists, "Merge button should be hidden for read-only user")

        let toggleStateButton = app.buttons["pr-toggle-state"]
        XCTAssertFalse(toggleStateButton.exists, "Close/Reopen button should be hidden for read-only user")
    }
}
