/**
 * @ai-summary React Query hook for user data export
 * @ai-context Downloads tar.gz archive with all user data
 */

import { useMutation } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { exportApi } from '../api/export.api';

interface ApiError {
  response?: {
    data?: {
      error?: string;
    };
  };
  message?: string;
}

export const useExportUserData = () => {
  return useMutation({
    mutationFn: () => exportApi.downloadUserExport(),
    onSuccess: (blob) => {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
      link.download = `motovaultpro_export_${timestamp}.tar.gz`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      toast.success('Data exported successfully');
    },
    onError: (error: ApiError) => {
      toast.error(error.response?.data?.error || 'Failed to export data');
    },
  });
};
