import { queryOptions } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import type { ProductFilters, ProductsResponse } from '@/features/products/api/types';
import type { UserFilters, UsersResponse } from '@/features/users/api/types';

async function getExampleProducts(filters: ProductFilters): Promise<ProductsResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.categories) searchParams.set('categories', filters.categories);
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.sort) searchParams.set('sort', filters.sort);

  return apiClient<ProductsResponse>(`/example/products?${searchParams.toString()}`);
}

async function getExampleUsers(filters: UserFilters): Promise<UsersResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.roles) searchParams.set('roles', filters.roles);
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.sort) searchParams.set('sort', filters.sort);

  const query = searchParams.toString();
  return apiClient<UsersResponse>(`/example/users${query ? `?${query}` : ''}`);
}

export const exampleProductKeys = {
  all: ['example-products'] as const,
  list: (filters: ProductFilters) => [...exampleProductKeys.all, 'list', filters] as const
};

export const exampleUserKeys = {
  all: ['example-users'] as const,
  list: (filters: UserFilters) => [...exampleUserKeys.all, 'list', filters] as const
};

export const exampleProductsQueryOptions = (filters: ProductFilters) =>
  queryOptions({
    queryKey: exampleProductKeys.list(filters),
    queryFn: () => getExampleProducts(filters)
  });

export const exampleUsersQueryOptions = (filters: UserFilters) =>
  queryOptions({
    queryKey: exampleUserKeys.list(filters),
    queryFn: () => getExampleUsers(filters)
  });
