import * as plugins from '../plugins.js';
import * as interfaces from '../../ts_interfaces/index.js';
import { appState } from './shared.js';
import { getActionContext } from './login.js';

export interface IConfigState {
  config: interfaces.requests.IConfigData | null;
  isLoading: boolean;
  error: string | null;
}

export const configStatePart = await appState.getStatePart<IConfigState>(
  'config',
  {
    config: null,
    isLoading: false,
    error: null,
  }
);

// Fetch Configuration Action (read-only)
export const fetchConfigurationAction = configStatePart.createAction(async (statePartArg): Promise<IConfigState> => {
  const context = getActionContext();
  const currentState = statePartArg.getState()!;
  if (!context.identity) return currentState;

  try {
    const configRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
      interfaces.requests.IReq_GetConfiguration
    >('/typedrequest', 'getConfiguration');

    const response = await configRequest.fire({
      identity: context.identity,
    });

    return {
      config: response.config,
      isLoading: false,
      error: null,
    };
  } catch (error: unknown) {
    return {
      ...currentState,
      isLoading: false,
      error: (error as Error).message || 'Failed to fetch configuration',
    };
  }
});

