import type { Middleware } from '@reduxjs/toolkit';

const AUDITABLE_ACTIONS = [
  'agentConfig/setActiveEngine',
  'agentConfig/updateEngineConfig',
  'riskRules/addRule',
  'riskRules/removeRule',
  'riskRules/updateRule',
  'permissionMatrix/updatePermission',
];

export const auditMiddleware: Middleware = (_store) => (next) => (action: any) => {
  const result = next(action);

  if (AUDITABLE_ACTIONS.includes(action.type)) {
    fetch('/api/proxy/audit-service/logs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        actionType: 'config_change',
        actorType: 'user',
        detail: {
          action: action.type,
          payload: action.payload,
          timestamp: new Date().toISOString(),
        },
      }),
    }).catch(console.error);
  }

  return result;
};
