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

interface PermissionMatrixState {
  roles: Array<{
    id: string;
    name: string;
    permissions: string[];
  }>;
  allPermissions: string[];
}

const initialState: PermissionMatrixState = {
  roles: [],
  allPermissions: [
    'dashboard:view',
    'agent:execute', 'agent:cancel', 'agent:config',
    'task:create', 'task:approve', 'task:view',
    'server:view', 'server:manage', 'server:ssh',
    'standing_order:create', 'standing_order:manage', 'standing_order:view',
    'audit:view',
    'tenant:manage', 'user:manage', 'engine:switch',
  ],
};

export const permissionMatrixSlice = createSlice({
  name: 'permissionMatrix',
  initialState,
  reducers: {
    setRoles: (state, action: PayloadAction<PermissionMatrixState['roles']>) => {
      state.roles = action.payload;
    },
    togglePermission: (state, action: PayloadAction<{ roleId: string; permission: string }>) => {
      const role = state.roles.find((r) => r.id === action.payload.roleId);
      if (role) {
        const idx = role.permissions.indexOf(action.payload.permission);
        if (idx === -1) {
          role.permissions.push(action.payload.permission);
        } else {
          role.permissions.splice(idx, 1);
        }
      }
    },
  },
});

export const permissionMatrixActions = permissionMatrixSlice.actions;
