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 IEmailOpsState {
  emails: interfaces.requests.IEmail[];
  isLoading: boolean;
  error: string | null;
  lastUpdated: number;
}

export const emailOpsStatePart = await appState.getStatePart<IEmailOpsState>(
  'emailOps',
  {
    emails: [],
    isLoading: false,
    error: null,
    lastUpdated: 0,
  },
  'soft'
);

// Email Operations Actions
// ============================================================================

// Fetch All Emails Action
export const fetchAllEmailsAction = emailOpsStatePart.createAction(async (statePartArg): Promise<IEmailOpsState> => {
  const context = getActionContext();
  const currentState = statePartArg.getState()!;
  if (!context.identity) return currentState;

  try {
    const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
      interfaces.requests.IReq_GetAllEmails
    >('/typedrequest', 'getAllEmails');

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

    return {
      emails: response.emails,
      isLoading: false,
      error: null,
      lastUpdated: Date.now(),
    };
  } catch (error) {
    return {
      ...currentState,
      isLoading: false,
      error: error instanceof Error ? error.message : 'Failed to fetch emails',
    };
  }
});

// ============================================================================
