import client from "./client";

export interface AuditLogOut {
  id: string;
  user_id: string | null;
  username: string | null;
  action: string;
  entity_type: string | null;
  entity_id: string | null;
  timestamp: string;
  details: Record<string, unknown> | null;
}

export interface AuditLogPage {
  items: AuditLogOut[];
  total: number;
  offset: number;
  limit: number;
}

export interface AuditLogFilters {
  user_id?: string;
  action?: string;
  entity_type?: string;
  start_date?: string;
  end_date?: string;
  offset?: number;
  limit?: number;
}

/** Fetch paginated audit logs with filters. */
export async function getAuditLogs(filters?: AuditLogFilters): Promise<AuditLogPage> {
  const params = new URLSearchParams();
  if (filters?.user_id) params.append("user_id", filters.user_id);
  if (filters?.action) params.append("action", filters.action);
  if (filters?.entity_type) params.append("entity_type", filters.entity_type);
  if (filters?.start_date) params.append("start_date", filters.start_date);
  if (filters?.end_date) params.append("end_date", filters.end_date);
  if (filters?.offset !== undefined) params.append("offset", String(filters.offset));
  if (filters?.limit !== undefined) params.append("limit", String(filters.limit));

  const { data } = await client.get<AuditLogPage>(
    `/audit-logs${params.toString() ? `?${params}` : ""}`
  );
  return data;
}

/** Fetch list of distinct actions. */
export async function getAuditActions(): Promise<string[]> {
  const { data } = await client.get<string[]>("/audit-logs/actions");
  return data;
}

/** Fetch list of distinct entity types. */
export async function getAuditEntityTypes(): Promise<string[]> {
  const { data } = await client.get<string[]>("/audit-logs/entity-types");
  return data;
}
