import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  fetchSpaces,
  createSpace,
  updateSpace,
  archiveSpace,
  type Space,
} from '../api';

const QK = ['spaces'] as const;

export function useSpaces() {
  return useQuery({
    queryKey: QK,
    queryFn: fetchSpaces,
    staleTime: 10_000,
  });
}

export function useCreateSpace() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: {
      title: string;
      description?: string;
      brandColor?: string | null;
      visibility?: Space['visibility'];
    }) => createSpace(input),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });
}

export function useUpdateSpace() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      patch,
    }: {
      id: string;
      patch: Partial<Pick<Space, 'title' | 'description' | 'brandColor' | 'visibility'>>;
    }) => updateSpace(id, patch),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });
}

export function useArchiveSpace() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => archiveSpace(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: QK }),
  });
}

export type { Space };
