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 ILogState {
  recentLogs: interfaces.data.ILogEntry[];
  isStreaming: boolean;
  filters: {
    level?: string[];
    category?: string[];
  };
}

export const logStatePart = await appState.getStatePart<ILogState>(
  'logs',
  {
    recentLogs: [],
    isStreaming: false,
    filters: {},
  },
  'soft'
);

// Fetch Recent Logs Action
export const fetchRecentLogsAction = logStatePart.createAction<{
  limit?: number;
  level?: 'debug' | 'info' | 'warn' | 'error';
  category?: 'smtp' | 'dns' | 'security' | 'system' | 'email';
}>(async (statePartArg, dataArg): Promise<ILogState> => {
  const context = getActionContext();
  if (!context.identity) return statePartArg.getState()!;

  const logsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
    interfaces.requests.IReq_GetRecentLogs
  >('/typedrequest', 'getRecentLogs');

  const response = await logsRequest.fire({
    identity: context.identity,
    limit: dataArg.limit || 100,
    level: dataArg.level,
    category: dataArg.category,
  });

  return {
    ...statePartArg.getState()!,
    recentLogs: response.logs,
  };
});

