import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '../lib/api';
import { PdfSettings, UpdatePdfSettingsDto } from '../types/settings';

/**
 * Fetch PDF settings
 */
export function usePdfSettings() {
  return useQuery<PdfSettings>({
    queryKey: ['settings', 'pdf'],
    queryFn: async () => {
      const { data } = await api.get('/settings/pdf');
      return data;
    },
  });
}

/**
 * Update PDF settings
 */
export function useUpdatePdfSettings() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (dto: UpdatePdfSettingsDto) => {
      const { data } = await api.patch('/settings/pdf', dto);
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings', 'pdf'] });
    },
  });
}

/**
 * Upload logo
 */
export function useUploadLogo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (file: File) => {
      const formData = new FormData();
      formData.append('logo', file);

      const { data } = await api.post('/settings/pdf/logo', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings', 'pdf'] });
    },
  });
}

/**
 * Delete logo
 */
export function useDeleteLogo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async () => {
      const { data } = await api.delete('/settings/pdf/logo');
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['settings', 'pdf'] });
    },
  });
}
