/**
 * Attachment and address hooks.
 */

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

export interface Attachment {
  id: string;
  entity_type: string;
  entity_id: string;
  filename: string;
  file_path: string;
  mime_type: string;
  file_size: number;
  uploaded_by?: string | null;
  created_at?: string;
  updated_at?: string;
}

export interface Address {
  id: string;
  entity_type: string;
  entity_id: string;
  label: string;
  address_type: string;
  street: string | null;
  street_number: string | null;
  city: string | null;
  zip: string | null;
  state: string | null;
  country: string | null;
  is_default: boolean;
  created_at?: string;
  updated_at?: string;
}

// Attachments
export function useAttachments(entityType?: string, entityId?: string) {
  return useQuery({
    queryKey: ['attachments', entityType, entityId],
    queryFn: () => {
      const params = new URLSearchParams();
      if (entityType) params.set('entity_type', entityType);
      if (entityId) params.set('entity_id', entityId);
      return apiGet<{ items: Attachment[]; total: number }>(`/attachments?${params.toString()}`);
    },
    enabled: !!entityType && !!entityId,
  });
}

export function useUploadAttachment() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ file, entityType, entityId }: { file: File; entityType: string; entityId: string }) => {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('entity_type', entityType);
      formData.append('entity_id', entityId);
      const response = await apiClient.post('/attachments', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['attachments'] });
    },
  });
}

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

// Addresses
export function useAddresses(entityType?: string, entityId?: string) {
  return useQuery({
    queryKey: ['addresses', entityType, entityId],
    queryFn: () =>
      apiGet<{ items: Address[]; total: number }>(
        `/addresses?entity_type=${entityType}&entity_id=${entityId}`
      ),
    enabled: !!entityType && !!entityId,
  });
}

export function useCreateAddress() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: Partial<Address> & { entity_type: string; entity_id: string }) =>
      apiPost('/addresses', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['addresses'] });
    },
  });
}

export function useUpdateAddress() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<Address> }) =>
      apiPatch(`/addresses/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['addresses'] });
    },
  });
}

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