/**
 * Composable for reloading data when server becomes reachable
 *
 * Handles the cache-first timing issue where local cached data is shown,
 * but we want to refresh from the server when it becomes available again.
 *
 * @req: UR-031 - Function offline on cached data
 * @req: DR-012 - Local database for media metadata cache
 *
 * @param reloadFn - Async function to call when server becomes reachable
 * @returns Object with markLoaded function to indicate initial load is complete
 *
 * @example
 * ```svelte
 * <script>
 *   const { markLoaded } = useServerReachabilityReload(async () => {
 *     await loadData();
 *   });
 *
 *   onMount(async () => {
 *     await loadData();
 *     markLoaded();
 *   });
 * </script>
 * ```
 */
export function useServerReachabilityReload(reloadFn: () => void | Promise<void>) {
  let hasLoadedOnce = false;
  let previousServerReachable = false;

  // Return an object with reactive getter/setter that can be used in Svelte components
  return {
    /**
     * Call this after initial data load to enable server reconnection tracking
     */
    markLoaded: () => {
      hasLoadedOnce = true;
    },

    /**
     * Call this in a $effect block to watch for server reconnection
     * Pass the current isServerReachable value and this will handle the logic
     */
    checkServerReachability: (isServerReachable: boolean) => {
      if (isServerReachable && !previousServerReachable && hasLoadedOnce) {
        // Server just became reachable and we've done an initial load
        // Trigger reload to get fresh data
        reloadFn();
      }

      previousServerReachable = isServerReachable;
    },
  };
}
