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

export interface SyncLog {
  id: number;
  table_name: string; // Mapping entity_type to table_name for UI compatibility
  record_id: string; // Mapping entity_id
  operation: string; // Mapping action
  status: string; // Hardcoding 'success' as audit logs imply successful actions
  error_message: string | null; // null
  retry_count: number; // 0
  created_at: string;
  synced_at: string | null; // null
  
  // Actual Audit Log fields
  user_email?: string;
  ip_address?: string;
  details?: string;
}

interface SyncLogsState {
  logs: SyncLog[];
  isLoading: boolean;
  error: string | null;
  fetchLogs: () => Promise<void>;
}

export const useSyncLogsStore = create<SyncLogsState>((set) => ({
  logs: [],
  isLoading: false,
  error: null,

  fetchLogs: async () => {
    set({ isLoading: true, error: null });

    try {
      const response = await api.get('/sync/logs');

      // Map sync logs to the expected SyncLog format for the UI
      const mappedLogs = (response.data.logs || []).map((log: any) => ({
        id: log.id,
        table_name: log.table_name || 'system',
        record_id: log.record_id ? String(log.record_id) : '-',
        operation: log.operation || 'push',
        status: log.status || 'success',
        error_message: log.error_message || null,
        retry_count: log.retry_count || 0,
        created_at: log.created_at,
        synced_at: log.synced_at || null
      }));

      set({
        logs: mappedLogs,
        isLoading: false
      });
    } catch (error: any) {
      set({
        error: error.response?.data?.error || 'Failed to fetch system logs',
        isLoading: false
      });
    }
  }
}));
