//
//  UITestSession.swift
//  suixinkanUITests
//
//  Created by Codex on 2026/6/26.
//

import XCTest

/// 全套件共享的已登录 App 会话，避免每个测试类重复冷启动登录。
enum UITestSession {
    private static var sharedApp: SuixinkanApp?

    /// 获取或创建已登录 App 实例。
    static func app(file: StaticString = #filePath, line: UInt = #line) throws -> SuixinkanApp {
        if let sharedApp {
            if sharedApp.application.state != .runningForeground {
                sharedApp.launch()
            }
            return sharedApp
        }

        let launched = try UITestAuthenticatedSession.launchLoggedIn(file: file, line: line)
        sharedApp = launched
        return launched
    }

    /// 以指定首页菜单直达参数重启 App，并复用 Keychain 登录态。
    @discardableResult
    static func relaunch(
        openMenu menuTitle: String,
        file: StaticString = #filePath,
        line: UInt = #line
    ) throws -> SuixinkanApp {
        sharedApp?.application.terminate()
        Thread.sleep(forTimeInterval: 1.0)

        let relaunched = try UITestAuthenticatedSession.launchLoggedIn(
            openMenuTitle: menuTitle,
            file: file,
            line: line
        )
        sharedApp = relaunched
        return relaunched
    }

    /// 以指定个人中心路由直达参数重启 App，并复用 Keychain 登录态。
    @discardableResult
    static func relaunch(
        openProfile route: String,
        file: StaticString = #filePath,
        line: UInt = #line
    ) throws -> SuixinkanApp {
        sharedApp?.application.terminate()
        Thread.sleep(forTimeInterval: 1.0)

        let relaunched = try UITestAuthenticatedSession.launchLoggedIn(
            openProfileRoute: route,
            file: file,
            line: line
        )
        sharedApp = relaunched
        return relaunched
    }

    /// 登录冒烟等用例清空本地状态后，使共享会话失效。
    static func invalidate() {
        sharedApp?.application.terminate()
        sharedApp = nil
    }
}
