/**
 * Assets Query Hooks
 *
 * React Query hooks for fetching and caching asset data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';
import type { Asset } from '../../types/entities';

interface AssetsListResponse {
  rows: Asset[];
  count: number;
}

interface AssetFilters {
  limit?: number;
  offset?: number;
  type?: string;
}

/**
 * Fetch assets for a project
 */
export function useAssetsQuery(
  projectId: string | undefined,
  filters?: AssetFilters,
) {
  const params = new URLSearchParams();
  if (projectId) params.set('projectId', projectId);
  if (filters?.limit) params.set('limit', String(filters.limit));
  if (filters?.offset) params.set('offset', String(filters.offset));
  if (filters?.type) params.set('type', filters.type);

  const queryString = params.toString();

  return useQuery({
    queryKey: queryKeys.assets.list(projectId || '', filters),
    queryFn: async (): Promise<Asset[]> => {
      const response = await axios.get<AssetsListResponse>(
        `assets?${queryString}`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Fetch single asset by ID
 */
export function useAssetQuery(assetId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.assets.detail(assetId || ''),
    queryFn: async (): Promise<Asset> => {
      const response = await axios.get<Asset>(`assets/${assetId}`);
      return response.data;
    },
    enabled: !!assetId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Update asset mutation
 */
export function useUpdateAssetMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      data,
    }: {
      id: string;
      data: Partial<Asset>;
    }): Promise<Asset> => {
      const response = await axios.put<Asset>(`assets/${id}`, {
        id,
        data,
      });
      return response.data;
    },
    onSuccess: (data, variables) => {
      queryClient.setQueryData(queryKeys.assets.detail(variables.id), data);
      queryClient.invalidateQueries({ queryKey: queryKeys.assets.all });
    },
  });
}

/**
 * Delete asset mutation
 */
export function useDeleteAssetMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (assetId: string): Promise<void> => {
      await axios.delete(`assets/${assetId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.assets.all });
    },
  });
}

export default useAssetsQuery;
