import { useCallback } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useCapabilities } from 'hooks/useCapabilities';

type AIHarnesses = {
  claudeCode: boolean;
  piMono: boolean;
};

type ServerSettings = {
  aiHarnesses?: AIHarnesses;
  plugins?: Record<string, boolean>;
};

const SETTINGS_KEY = ['SERVER_SETTINGS'];

export const useServerSettings = () => {
  const client = useClient();
  const queryClient = useQueryClient();

  // `/server-settings` is the `server-admin` capability: owner only, and not grantable at any level. This
  // hook is mounted by shell components that every account loads, so without the guard a member's first
  // paint fired a 403 at it.
  const { isOwner } = useCapabilities();

  const { data: settings, isLoading } = useQuery({
    queryKey: SETTINGS_KEY,
    enabled: isOwner,
    queryFn: () => client.get<ServerSettings>('/server-settings/settings'),
  });

  const aiHarnesses = settings?.aiHarnesses;
  const plugins = settings?.plugins;
  const saveSettings = useCallback(
    async (update: Partial<ServerSettings>) => {
      const result = await client.put<ServerSettings>('/server-settings', update);
      queryClient.setQueryData(SETTINGS_KEY, result);
    },
    [client, queryClient],
  );

  return { aiHarnesses, plugins, isLoading, saveSettings };
};
