/**
 * Client API per Audit Log.
 */

import apiClient from './client'
import type { PaginatedResponse } from '@/types/api.types'

export interface AuditLogEntry {
  id: number
  tenant_id: string | null
  user_id: string | null
  user_email: string | null
  user_full_name: string | null
  action: string
  resource_type: string | null
  resource_id: string | null
  ip_address: string | null
  user_agent: string | null
  payload: Record<string, unknown> | null
  outcome: 'success' | 'failure'
  occurred_at: string
}

export type AuditLogListResponse = PaginatedResponse<AuditLogEntry>

export interface AuditLogParams {
  page?: number
  page_size?: number
  action?: string
  user_id?: string
  outcome?: 'success' | 'failure'
  date_from?: string
  date_to?: string
  resource_type?: string
  tenant_id?: string
}

export const auditLogApi = {
  list: (params: AuditLogParams = {}): Promise<AuditLogListResponse> =>
    apiClient
      .get<AuditLogListResponse>('/audit-log', { params })
      .then((r) => r.data),

  /**
   * Esporta i log come file (CSV o PDF).
   * Restituisce un Blob per il download lato browser.
   */
  export: async (
    format: 'csv' | 'pdf',
    params: Omit<AuditLogParams, 'page' | 'page_size'> = {},
  ): Promise<Blob> => {
    const response = await apiClient.get('/audit-log/export', {
      params: { format, ...params },
      responseType: 'blob',
    })
    return response.data as Blob
  },
}
