/**
 * @ai-summary React Query hook for user data import
 * @ai-context Manages import flow: preview -> execute with mode selection
 */

import { useMutation } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { importApi } from '../api/import.api';
import { ImportPreview, ImportResult } from '../types/import.types';

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

export const useImportPreview = () => {
  return useMutation<ImportPreview, ApiError, File>({
    mutationFn: (file: File) => importApi.getPreview(file),
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to generate preview'
      );
    },
  });
};

export const useImportUserData = () => {
  return useMutation<
    ImportResult,
    ApiError,
    { file: File; mode: 'merge' | 'replace' }
  >({
    mutationFn: ({ file, mode }) => importApi.executeImport(file, mode),
    onSuccess: (result) => {
      if (result.success) {
        const { imported, updated, skipped } = result.summary;
        toast.success(
          `Import complete: ${imported} imported, ${updated} updated, ${skipped} skipped`
        );
      } else {
        toast.error('Import completed with errors. Check results for details.');
      }
    },
    onError: (error: ApiError) => {
      toast.error(
        error.response?.data?.message ||
          error.response?.data?.error ||
          'Failed to import data'
      );
    },
  });
};
