'use client';

import { useQuery, useMutation, useQueryClient, UseQueryOptions } from '@tanstack/react-query';
import { apiClient } from './api-client';

/**
 * GET 请求 hook — 基于 @tanstack/react-query
 *
 * @example
 * const { data, isLoading, error } = useApi<DashboardStats>('/api/v1/admin/dashboard/stats');
 */
export function useApi<T = unknown>(
  url: string | null,
  options?: Omit<UseQueryOptions<T, Error>, 'queryKey' | 'queryFn'> & {
    params?: Record<string, unknown>;
  },
) {
  const { params, ...queryOptions } = options ?? {};

  return useQuery<T, Error>({
    queryKey: [url, params],
    queryFn: async () => {
      if (!url) throw new Error('URL is required');
      return apiClient.get<T>(url, { params });
    },
    enabled: !!url,
    staleTime: 30_000,
    ...queryOptions,
  });
}

/**
 * POST/PUT/DELETE mutation hook
 *
 * @example
 * const { mutateAsync } = useApiMutation<void>('POST', '/api/v1/admin/coupons/123/approve');
 * await mutateAsync({ reason: 'Approved' });
 */
export function useApiMutation<T = unknown>(
  method: 'POST' | 'PUT' | 'PATCH' | 'DELETE',
  url: string,
  options?: { invalidateKeys?: string[] },
) {
  const queryClient = useQueryClient();

  return useMutation<T, Error, unknown>({
    mutationFn: async (data?: unknown) => {
      switch (method) {
        case 'POST':
          return apiClient.post<T>(url, data);
        case 'PUT':
          return apiClient.put<T>(url, data);
        case 'PATCH':
          return apiClient.patch<T>(url, data);
        case 'DELETE':
          return apiClient.delete<T>(url);
      }
    },
    onSuccess: () => {
      options?.invalidateKeys?.forEach((key) => {
        queryClient.invalidateQueries({ queryKey: [key] });
      });
    },
  });
}
