import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { adminFetch } from './admin-api';
import { useRefreshInterval } from '../use-refresh-interval';

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

export interface DatabaseStatus {
  connected: boolean;
  version: string | null;
  host: string | null;
  schema: string | null;
}

export interface PoolStats {
  activeConnections: number;
  idleConnections: number;
  threadsAwaitingConnection: number;
  connectionTimeout: number;
  maximumPoolSize: number;
}

export interface TableInfo {
  tableName: string;
  rowCount: number;
  dataSize: string;
  indexSize: string;
  dataSizeBytes: number;
  indexSizeBytes: number;
}

export interface ActiveQuery {
  pid: number;
  durationSeconds: number;
  state: string;
  query: string;
}

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

export function useDatabaseStatus() {
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['admin', 'database', 'status'],
    queryFn: () => adminFetch<DatabaseStatus>('/database/status'),
    refetchInterval,
  });
}

export function useConnectionPool() {
  const refetchInterval = useRefreshInterval(10_000);
  return useQuery({
    queryKey: ['admin', 'database', 'pool'],
    queryFn: () => adminFetch<PoolStats>('/database/pool'),
    refetchInterval,
  });
}

export function useDatabaseTables() {
  const refetchInterval = useRefreshInterval(60_000);
  return useQuery({
    queryKey: ['admin', 'database', 'tables'],
    queryFn: () => adminFetch<TableInfo[]>('/database/tables'),
    refetchInterval,
  });
}

export function useActiveQueries() {
  const refetchInterval = useRefreshInterval(5_000);
  return useQuery({
    queryKey: ['admin', 'database', 'queries'],
    queryFn: () => adminFetch<ActiveQuery[]>('/database/queries'),
    refetchInterval,
  });
}

// ── Mutation Hooks ─────────────────────────────────────────────────────

export function useKillQuery() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (pid: number) =>
      adminFetch<void>(`/database/queries/${pid}/kill`, { method: 'POST' }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['admin', 'database', 'queries'] });
    },
  });
}
