import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  listDatabases,
  listSchemas,
  listTables,
  listViews,
  listFunctions,
  listSequences,
  switchDatabase,
  getColumnDetails,
} from "@/lib/tauri";
import type { ConnectionConfig } from "@/types";

export function useDatabases(connectionId: string | null) {
  return useQuery({
    queryKey: ["databases", connectionId],
    queryFn: () => listDatabases(connectionId!),
    enabled: !!connectionId,
    staleTime: 5 * 60 * 1000,
  });
}

export function useSwitchDatabase() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ config, database }: { config: ConnectionConfig; database: string }) =>
      switchDatabase(config, database),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["schemas"] });
      queryClient.invalidateQueries({ queryKey: ["tables"] });
      queryClient.invalidateQueries({ queryKey: ["views"] });
      queryClient.invalidateQueries({ queryKey: ["functions"] });
      queryClient.invalidateQueries({ queryKey: ["sequences"] });
    },
  });
}

export function useSchemas(connectionId: string | null) {
  return useQuery({
    queryKey: ["schemas", connectionId],
    queryFn: () => listSchemas(connectionId!),
    enabled: !!connectionId,
    staleTime: 5 * 60 * 1000,
  });
}

export function useTables(connectionId: string | null, schema: string) {
  return useQuery({
    queryKey: ["tables", connectionId, schema],
    queryFn: () => listTables(connectionId!, schema),
    enabled: !!connectionId && !!schema,
    staleTime: 5 * 60 * 1000,
  });
}

export function useViews(connectionId: string | null, schema: string) {
  return useQuery({
    queryKey: ["views", connectionId, schema],
    queryFn: () => listViews(connectionId!, schema),
    enabled: !!connectionId && !!schema,
    staleTime: 5 * 60 * 1000,
  });
}

export function useFunctions(connectionId: string | null, schema: string) {
  return useQuery({
    queryKey: ["functions", connectionId, schema],
    queryFn: () => listFunctions(connectionId!, schema),
    enabled: !!connectionId && !!schema,
    staleTime: 5 * 60 * 1000,
  });
}

export function useSequences(connectionId: string | null, schema: string) {
  return useQuery({
    queryKey: ["sequences", connectionId, schema],
    queryFn: () => listSequences(connectionId!, schema),
    enabled: !!connectionId && !!schema,
    staleTime: 5 * 60 * 1000,
  });
}

export function useColumnDetails(connectionId: string | null, schema: string | null, table: string | null) {
  return useQuery({
    queryKey: ["column-details", connectionId, schema, table],
    queryFn: () => getColumnDetails(connectionId!, schema!, table!),
    enabled: !!connectionId && !!schema && !!table,
    staleTime: 5 * 60 * 1000,
  });
}
