/**
 * Custom fields API hooks — merge plugin definitions with stored values.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPatch } from './client';

export interface CustomFieldDefinition {
  name: string;
  label: string;
  label_key: string;
  field_type: 'text' | 'number' | 'date' | 'select' | 'multiselect' | 'boolean';
  options: string[];
  default_value: any;
  required: boolean;
  entity: string;
  plugin: string;
  value: any;
}

export interface CustomFieldsResponse {
  fields: CustomFieldDefinition[];
}

export function useCustomFields(contactId?: string) {
  return useQuery({
    queryKey: ['custom-fields', contactId],
    queryFn: () => apiGet<CustomFieldsResponse>(`/contacts/${contactId}/custom-fields`),
    enabled: !!contactId,
  });
}

export function useUpdateCustomFields() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ contactId, values }: { contactId: string; values: Record<string, any> }) =>
      apiPatch<CustomFieldsResponse>(`/contacts/${contactId}/custom-fields`, { values }),
    onSuccess: (_data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['custom-fields', variables.contactId] });
    },
  });
}
