/**
 * Tells every mounted screen to read again after a manual sync.
 *
 * The PHP side has already fetched the saved copies again. Screens keep their
 * own data in React state, so without this they would keep showing the old
 * list until the merchant left and came back.
 */

import { api } from './api';
import { forgetScreens } from './screenCache';

type Listener = () => void;

const listeners = new Set< Listener >();

export function onSynced( listener: Listener ): () => void {
	listeners.add( listener );

	return () => {
		listeners.delete( listener );
	};
}

export function notifySynced(): void {
	// Screens not open now load the synced data when next opened.
	forgetScreens();
	listeners.forEach( ( listener ) => listener() );
}

/**
 * Fetch the store from RazorBooking again: one request to this site, which
 * makes one to RazorBooking (Razorbooking_Sync).
 */
export async function syncAll(): Promise< void > {
	await api.post( 'sync' );
}
