import apiClient from '../../../shared/services/apiClient';

export interface AuditLog {
  id: number;
  user_id?: number;
  action: string;
  resource_type: string;
  resource_id?: number;
  ip_address?: string;
  user_agent?: string;
  request_id?: string;
  details?: Record<string, unknown>;
  status: string;
  error_message?: string;
  created_at: string;
  user?: {
    id: number;
    full_name: string;
    email: string;
  };
}

export interface AuditLogListResponse {
  status: string;
  data: {
    logs: AuditLog[];
    pagination: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  };
}

export interface AuditLogStatsResponse {
  status: string;
  data: {
    total: number;
    by_status: {
      success: number;
      failed: number;
      error: number;
    };
    top_actions: Array<{
      action: string;
      count: number;
    }>;
    top_resource_types: Array<{
      resource_type: string;
      count: number;
    }>;
  };
}

export interface AuditLogFilters {
  action?: string;
  resource_type?: string;
  user_id?: number;
  status?: string;
  search?: string;
  start_date?: string;
  end_date?: string;
  page?: number;
  limit?: number;
}

class AuditService {
  
  async getAuditLogs(filters: AuditLogFilters = {}): Promise<AuditLogListResponse> {
    const params = new URLSearchParams();
    
    if (filters.action) params.append('action', filters.action);
    if (filters.resource_type) params.append('resource_type', filters.resource_type);
    if (filters.user_id) params.append('user_id', filters.user_id.toString());
    if (filters.status) params.append('status', filters.status);
    if (filters.search) params.append('search', filters.search);
    if (filters.start_date) params.append('start_date', filters.start_date);
    if (filters.end_date) params.append('end_date', filters.end_date);
    if (filters.page) params.append('page', filters.page.toString());
    if (filters.limit) params.append('limit', filters.limit.toString());

    const response = await apiClient.get(`/audit-logs/?${params.toString()}`);
    return response.data;
  }

  
  async getAuditLogById(id: number): Promise<{ status: string; data: { log: AuditLog } }> {
    const response = await apiClient.get(`/audit-logs/${id}`);
    return response.data;
  }

  
  async getAuditStats(startDate?: string, endDate?: string): Promise<AuditLogStatsResponse> {
    const params = new URLSearchParams();
    if (startDate) params.append('start_date', startDate);
    if (endDate) params.append('end_date', endDate);

    const response = await apiClient.get(`/audit-logs/stats?${params.toString()}`);
    return response.data;
  }
}

export const auditService = new AuditService();
export default auditService;

