/**
 * Element Defaults Query Hooks
 *
 * React Query hooks for fetching project element defaults.
 */

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';
import type {
  CanvasElementType,
  CanvasElement,
  NormalizedElementDefault,
} from '../../types/constructor';
import {
  normalizeElementDefault,
  buildElementDefaultsMap,
} from '../../types/constructor';

interface ElementDefaultsResponse {
  rows: Record<string, unknown>[];
  count: number;
}

/**
 * Fetch project element defaults and transform to a type-indexed map
 */
export function useElementDefaultsQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.elementDefaults.project(projectId || ''),
    queryFn: async (): Promise<
      Partial<Record<CanvasElementType, Partial<CanvasElement>>>
    > => {
      const response = await axios.get<ElementDefaultsResponse>(
        `project-element-defaults?projectId=${projectId}&limit=200&page=0&sort=asc&field=sort_order`,
      );

      // Process and normalize the defaults
      const normalizedDefaults = response.data.rows
        .map((row) => normalizeElementDefault(row))
        .filter((d): d is NormalizedElementDefault => d !== null);

      return buildElementDefaultsMap(normalizedDefaults);
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

export default useElementDefaultsQuery;
