import XCTest

class ForgejoUITestBase: XCTestCase, UITestNavigating {

    var app: XCUIApplication!
    var serverURL: String!

    override func setUpWithError() throws {
        continueAfterFailure = true

        guard let url = Self.resolveTestServerURL(),
            !url.isEmpty
        else {
            throw XCTSkip("Integration server not running")
        }
        serverURL = url

        // Force portrait orientation for consistent vertical space across test runs
        XCUIDevice.shared.orientation = .portrait

        app = XCUIApplication()
        app.launchArguments += [
            "-dev_serverURL", serverURL,
            "-dev_username", "testadmin",
            "-dev_password", "admin1234",
        ]
    }

    // MARK: - Server URL Resolution

    /// Resolves the Forgejo test server URL from simulator-specific temp files.
    /// Each simulator gets its own file (keyed by device name) so parallel test
    /// groups on different simulators can target different Forgejo instances.
    static func resolveTestServerURL() -> String? {
        let deviceName = (ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] ?? "")
            .replacingOccurrences(of: " ", with: "_")
        let specificPath = "/tmp/forgejo_test_url_\(deviceName).txt"
        let genericPath = "/tmp/forgejo_test_url.txt"

        return ((try? String(contentsOfFile: specificPath, encoding: .utf8))
            ?? (try? String(contentsOfFile: genericPath, encoding: .utf8)))
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
    }

    // MARK: - Test Token Resolution

    /// Resolves the API token created by the seed script for token-based auth tests.
    static func resolveTestToken() -> String? {
        let deviceName = (ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] ?? "")
            .replacingOccurrences(of: " ", with: "_")
        let specificPath = "/tmp/forgejo_test_token_\(deviceName).txt"
        let genericPath = "/tmp/forgejo_test_token.txt"

        return ((try? String(contentsOfFile: specificPath, encoding: .utf8))
            ?? (try? String(contentsOfFile: genericPath, encoding: .utf8)))
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
    }

    // MARK: - Helpers

    /// Launches the app and waits for HomeView to appear via auto-login.
    func loginAndWaitForHome() {
        app.launch()
        let reposTab = app.tabBars.buttons["Repositories"]
        XCTAssertTrue(reposTab.waitForExistence(timeout: 15), "HomeView did not appear after auto-login")
    }

    func navigateToRepoDetail(_ repoName: String = "test-repo") {
        app.tabBars.buttons["Repositories"].tap()

        let repoCell = app.staticTexts[repoName].firstMatch
        XCTAssertTrue(repoCell.waitForExistence(timeout: 10))
        repoCell.tap()
    }

}
