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

type AccessPolicy = {
  allowedModels: string[];
};

const QUERY_KEY = ['ACCESS_POLICY'];

export function useAccessPolicy() {
  const client = useClient();
  const { isAuthenticated } = useAuth();
  // Under `/server-settings`, so `server-admin`: owner only. Authentication alone was never the right gate.
  const { isOwner } = useCapabilities();
  const queryClient = useQueryClient();

  const { data: policy = { allowedModels: [] } } = useQuery<AccessPolicy>({
    queryKey: QUERY_KEY,
    enabled: isAuthenticated && isOwner,
    queryFn: () => client.get<AccessPolicy>('/server-settings/chat-providers/access-policy'),
    staleTime: 5 * 60 * 1000,
  });

  const savePolicy = useCallback(
    async (newPolicy: AccessPolicy) => {
      queryClient.setQueryData(QUERY_KEY, newPolicy);
      await client.put('/server-settings/chat-providers/access-policy', newPolicy);
    },
    [client, queryClient],
  );

  return { policy, savePolicy };
}
