'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '@/lib/api/carteras';

export function useCarteras() {
  return useQuery({
    queryKey: ['carteras'],
    queryFn: () => api.getCarteras().then(r => r.data),
  });
}

export function useSupervisores() {
  return useQuery({
    queryKey: ['cartera-supervisores'],
    queryFn: () => api.getSupervisores().then(r => r.data),
  });
}

export function useCreateCartera() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: api.createCartera,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['carteras'] }),
  });
}

export function useDeleteCartera() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: api.deleteCartera,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['carteras'] }),
  });
}

export function useCarteraEntidades(carteraId: string | null) {
  return useQuery({
    queryKey: ['cartera-entidades', carteraId],
    queryFn: () => api.getCarteraEntidades(carteraId!).then(r => r.data),
    enabled: !!carteraId,
  });
}

export function useSubcarteras(carteraId: string | null) {
  return useQuery({
    queryKey: ['subcarteras', carteraId],
    queryFn: () => api.getSubcarteras(carteraId!).then(r => r.data),
    enabled: !!carteraId,
  });
}

export function useCreateSubcartera() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ carteraId, ...payload }: { carteraId: string; nombre: string; descripcion?: string; auxiliarUserId: string }) =>
      api.createSubcartera(carteraId, payload),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['subcarteras'] });
      qc.invalidateQueries({ queryKey: ['carteras'] });
    },
  });
}
