/**
 * Admin API - Audit Logs Management
 */

import { api as client } from '../apiClient';

export interface AuditLog {
  id: string;
  userId: string;
  username?: string;
  action: string;
  resource: string;
  resourceType?: string;
  resourceId?: string;
  ipAddress?: string;
  userAgent?: string;
  details: any;
  createdAt: string;
}

export interface PaginationParams {
  page?: number;
  pageSize?: number;
}

export interface PaginatedResponse<T> {
  items: T[];
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface AuditLogListParams extends PaginationParams {
  userId?: string;
  action?: string;
  resourceType?: string;
  startDate?: string;
  endDate?: string;
}

export const listAuditLogs = async (params: AuditLogListParams): Promise<PaginatedResponse<AuditLog>> => {
  const response = await client.get('/api/admin/audit-logs', { params });
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const getAuditLog = async (id: string): Promise<AuditLog> => {
  const response = await client.get(`/api/admin/audit-logs/${id}`);
  return response.data;
};

export interface ExportAuditLogsParams {
  format?: string;
  userId?: string;
  action?: string;
  resourceType?: string;
  startDate?: string;
  endDate?: string;
}

export interface ExportedBlob {
  content: Blob;
  filename: string;
}

export const exportAuditLogs = async (params: ExportAuditLogsParams): Promise<ExportedBlob> => {
  const response = await client.get('/api/admin/audit-logs/export', { params, responseType: 'blob' });
  // Extract filename from Content-Disposition header if available
  const contentDisposition = response.headers['content-disposition'];
  let filename = 'audit-logs.csv';
  if (contentDisposition) {
    const match = contentDisposition.match(/filename="(.+)"/);
    if (match) {
      filename = match[1];
    }
  }
  return {
    content: response.data,
    filename
  };
};
