/**
 * Contact CRUD hooks (legacy contact model — not unified contacts).
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPost, apiPatch, apiDelete, apiPut } from './client';
import { PaginatedResponse, Contact, ContactDetail } from './types';
import { ContactFolder } from './contactFolders';

export function useContacts(page = 1, pageSize = 25, search?: string) {
  const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
  if (search) params.set('search', search);
  return useQuery({
    queryKey: ['contacts', page, pageSize, search],
    queryFn: () =>
      apiGet<PaginatedResponse<Contact>>(`/contacts?${params.toString()}`),
  });
}

export function useContact(id?: string) {
  return useQuery({
    queryKey: ['contacts', id],
    queryFn: () => apiGet<ContactDetail>(`/contacts/${id}`),
    enabled: !!id,
  });
}

export function useCreateContact() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: Partial<Contact> & { company_ids?: string[] }) =>
      apiPost('/contacts', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
    },
  });
}

export function useUpdateContact() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Contact> & { company_ids?: string[] } }) =>
      apiPatch(`/contacts/${id}`, data),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
      queryClient.invalidateQueries({ queryKey: ['contacts', variables.id] });
    },
  });
}

export function useDeleteContact() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => apiDelete(`/contacts/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contacts'] });
    },
  });
}

// ── Contact Folders ──

export function useContactFolders() {
  return useQuery({
    queryKey: ['contactFolders'],
    queryFn: () => apiGet<ContactFolder[]>('/contact-folders'),
  });
}

export function useCreateContactFolder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: { name: string; parent_id?: string }) => apiPost('/contact-folders', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contactFolders'] });
    },
  });
}

export function useUpdateContactFolder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: { name?: string; parent_id?: string | null; sort_order?: number } }) =>
      apiPut(`/contact-folders/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contactFolders'] });
    },
  });
}

export function useDeleteContactFolder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => apiDelete(`/contact-folders/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['contactFolders'] });
    },
  });
}

export function useMoveContactToFolder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ contactId, folderId }: { contactId: string; folderId: string | null }) =>
      apiPut(`/contact-folders/contacts/${contactId}/move`, { folder_id: folderId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unifiedContacts'] });
      queryClient.invalidateQueries({ queryKey: ['contactFolders'] });
    },
  });
}
