import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface RunbookEditorState {
  currentRunbook: {
    id?: string;
    name: string;
    description: string;
    promptTemplate: string;
    allowedTools: string[];
    maxRiskLevel: number;
    autoApprove: boolean;
  } | null;
  isDirty: boolean;
  undoStack: string[];
  redoStack: string[];
}

const initialState: RunbookEditorState = {
  currentRunbook: null,
  isDirty: false,
  undoStack: [],
  redoStack: [],
};

export const runbookEditorSlice = createSlice({
  name: 'runbookEditor',
  initialState,
  reducers: {
    loadRunbook: (state, action: PayloadAction<RunbookEditorState['currentRunbook']>) => {
      state.currentRunbook = action.payload;
      state.isDirty = false;
      state.undoStack = [];
      state.redoStack = [];
    },
    updatePromptTemplate: (state, action: PayloadAction<string>) => {
      if (state.currentRunbook) {
        state.undoStack.push(state.currentRunbook.promptTemplate);
        state.currentRunbook.promptTemplate = action.payload;
        state.isDirty = true;
        state.redoStack = [];
      }
    },
    undo: (state) => {
      if (state.currentRunbook && state.undoStack.length > 0) {
        state.redoStack.push(state.currentRunbook.promptTemplate);
        state.currentRunbook.promptTemplate = state.undoStack.pop()!;
      }
    },
    redo: (state) => {
      if (state.currentRunbook && state.redoStack.length > 0) {
        state.undoStack.push(state.currentRunbook.promptTemplate);
        state.currentRunbook.promptTemplate = state.redoStack.pop()!;
      }
    },
    resetEditor: () => initialState,
  },
});

export const runbookEditorActions = runbookEditorSlice.actions;
