function wait() {
    return Promise.resolve()
}

export function sleep(interval = 0) {
    return new Promise<void>(resolve => {
        setTimeout(() => resolve(), interval)
    })
}

/**
 * @param process 实际运行的 "测试逻辑"
 * @param step
 */
export function run(
    process: (collectPromise: (...promise: Array<Promise<any>>) => {
        promise: Promise<void>
    }) => (Promise<void> | void),
    {
        step = 10,
        total = 2000,
        asyncStep = 3,
    }: {
        step?: number
        total?: number
        asyncStep?: number
    } = {}
) {
    return async () => {
        let isProcessed = false
        let error: any = null

        const collectPromise = (...promiseList: Array<Promise<any>>) => {
            return {
                promise: Promise.all(promiseList)
                    .then(() => undefined)
                    .catch(e => {
                        console.log(e)
                        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
                        throw e
                    }),
            }
        }

        void Promise
            .resolve(process(collectPromise))
            .then(() => {
                isProcessed = true
            })
            .catch((e) => {
                // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
                error = error || e
            })

        for (let i = 0; i < total / step; i++) {
            jest.advanceTimersByTime(step)
            for (let j = 0; j < asyncStep; j++) {
                await wait()
            }
            if (isProcessed) {
                return
            }
            if (error !== null) {
                throw error
            }
        }

        throw new Error('Timeout')
    }
}
