import { create } from 'zustand';
import api from './api';

export interface AuditLog {
  id: number;
  uid: string;
  user_id: number | null;
  user_email: string | null;
  action: string;
  entity_type: string | null;
  entity_id: string | null;
  old_data: string | null;
  new_data: string | null;
  ip_address: string | null;
  user_agent: string | null;
  created_at: string;
}

interface AuditState {
  logs: AuditLog[];
  total: number;
  isLoading: boolean;
  error: string | null;
  fetchLogs: (filters?: any) => Promise<void>;
  getLogDetails: (id: number) => Promise<AuditLog>;
}

export const useAuditStore = create<AuditState>((set) => ({
  logs: [],
  total: 0,
  isLoading: false,
  error: null,

  fetchLogs: async (filters = {}) => {
    set({ isLoading: true, error: null });
    try {
      const response = await api.get('/audit', { params: filters });
      set({ 
        logs: response.data.logs, 
        total: response.data.pagination.total,
        isLoading: false 
      });
    } catch (error: any) {
      set({ error: error.response?.data?.error || 'Failed to fetch audit logs', isLoading: false });
    }
  },

  getLogDetails: async (id: number) => {
    try {
      const response = await api.get(`/audit/${id}`);
      return response.data;
    } catch (error: any) {
      throw new Error(error.response?.data?.error || 'Failed to fetch log details');
    }
  },
}));
