import { useQuery } from '@tanstack/react-query';
import { adminFetch } from './admin-api';

// ── Types ──────────────────────────────────────────────────────────────

export interface AuditEvent {
  id: number;
  timestamp: string;
  username: string;
  action: string;
  category: string;
  target: string;
  detail: Record<string, unknown> | null;
  result: string;
  ipAddress: string;
  userAgent: string;
}

export interface AuditLogParams {
  username?: string;
  category?: string;
  search?: string;
  from?: string;
  to?: string;
  sort?: string;
  order?: string;
  page?: number;
  size?: number;
}

export interface AuditLogResponse {
  items: AuditEvent[];
  totalCount: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// ── Query Hooks ────────────────────────────────────────────────────────

export function useAuditLog(params: AuditLogParams = {}) {
  return useQuery({
    queryKey: ['admin', 'audit', params],
    queryFn: () => {
      const qs = new URLSearchParams();
      if (params.username) qs.set('username', params.username);
      if (params.category) qs.set('category', params.category);
      if (params.search) qs.set('search', params.search);
      if (params.from) qs.set('from', params.from);
      if (params.to) qs.set('to', params.to);
      if (params.sort) qs.set('sort', params.sort);
      if (params.order) qs.set('order', params.order);
      if (params.page !== undefined) qs.set('page', String(params.page));
      if (params.size !== undefined) qs.set('size', String(params.size));
      const query = qs.toString();
      return adminFetch<AuditLogResponse>(`/audit${query ? `?${query}` : ''}`);
    },
    placeholderData: (prev) => prev,
  });
}
