import { api } from './endpoints';
import type { Fix, FixRequest } from './types/fixes';

export type FixProgressListener = ( fix: Fix ) => void;

export async function applyFix(
	request: FixRequest,
	onProgress?: FixProgressListener,
	stopSignal?: AbortSignal
): Promise< Fix > {
	let fix = await api.createFix( request );

	onProgress?.( fix );

	while ( fix.state === 'running' && stopSignal?.aborted !== true ) {
		fix = await api.runFix( fix.id );
		onProgress?.( fix );
	}

	return fix;
}

export async function undoFix( fixId: number ): Promise< Fix > {
	let fix = await api.undoFix( fixId );

	while ( fix.state === 'undoing' ) {
		fix = await api.undoFix( fixId );
	}

	return fix;
}
