// SPEC: pikasTech/HWLAB#2345 Workbench Pinia Colada migration.
// Responsibility: Store Workbench reducer projection in Pinia Colada cache instead of a local Pinia ref.

import { computed, type ComputedRef } from "vue";
import { useQuery, useQueryCache, type QueryCache } from "@pinia/colada";
import { workbenchColadaKeys } from "./workbench-colada-keys";
import { createWorkbenchServerState, reduceWorkbenchServerState, type WorkbenchServerAction, type WorkbenchServerState } from "./workbench-server-state";

export interface WorkbenchColadaReducer {
  queryCache: QueryCache;
  serverState: ComputedRef<WorkbenchServerState>;
  readServerState: () => WorkbenchServerState;
  replaceServerState: (project: (state: WorkbenchServerState) => WorkbenchServerState) => void;
  reduceServerState: (action: WorkbenchServerAction) => void;
}

export function useWorkbenchColadaReducer(): WorkbenchColadaReducer {
  const queryCache = useQueryCache();
  const key = workbenchColadaKeys.serverState();
  const serverStateQuery = useQuery<WorkbenchServerState, Error, WorkbenchServerState>({
    key,
    query: async () => queryCache.getQueryData<WorkbenchServerState>(key) ?? createWorkbenchServerState(),
    initialData: createWorkbenchServerState,
    enabled: false
  });
  const serverState = computed<WorkbenchServerState>(() => serverStateQuery.data.value ?? createWorkbenchServerState());

  function readServerState(): WorkbenchServerState {
    return queryCache.getQueryData<WorkbenchServerState>(key) ?? serverState.value;
  }

  function replaceServerState(project: (state: WorkbenchServerState) => WorkbenchServerState): void {
    queryCache.setQueryData<WorkbenchServerState>(key, (source) => project(source ?? createWorkbenchServerState()));
  }

  function reduceServerState(action: WorkbenchServerAction): void {
    replaceServerState((source) => reduceWorkbenchServerState(source, action));
  }

  return { queryCache, serverState, readServerState, replaceServerState, reduceServerState };
}
