import { useQuery } from '@tanstack/react-query';
import { api } from '../client';
import { useEnvironmentStore } from '../environment-store';

export interface DiagramNode {
  id?: string;
  label?: string;
  type?: string;
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  children?: DiagramNode[];
  endpointUri?: string;
}

export interface DiagramEdge {
  sourceId: string;
  targetId: string;
  label?: string;
  points: number[][];
}

export interface DiagramLayout {
  width?: number;
  height?: number;
  nodes?: DiagramNode[];
  edges?: DiagramEdge[];
}

export function useDiagramLayout(
  contentHash: string | null,
  direction: 'LR' | 'TB' = 'LR',
) {
  return useQuery({
    queryKey: ['diagrams', 'layout', contentHash, direction],
    queryFn: async () => {
      const { data, error } = await api.GET('/diagrams/{contentHash}/render', {
        params: {
          path: { contentHash: contentHash! },
          query: { direction },
        },
        headers: { Accept: 'application/json' },
      });
      if (error) throw new Error('Failed to load diagram layout');
      return data as DiagramLayout;
    },
    enabled: !!contentHash,
  });
}

export function useDiagramByRoute(
  application: string | undefined,
  routeId: string | undefined,
  direction: 'LR' | 'TB' = 'LR',
) {
  const environment = useEnvironmentStore((s) => s.environment);
  return useQuery({
    queryKey: ['diagrams', 'byRoute', environment, application, routeId, direction],
    queryFn: async () => {
      const { useAuthStore } = await import('../../auth/auth-store');
      const { config: appConfig } = await import('../../config');
      const token = useAuthStore.getState().accessToken;
      const url = `${appConfig.apiBaseUrl}/environments/${encodeURIComponent(environment!)}` +
        `/apps/${encodeURIComponent(application!)}` +
        `/routes/${encodeURIComponent(routeId!)}/diagram?direction=${direction}`;
      const res = await fetch(url, {
        headers: {
          Accept: 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
          'X-Cameleer-Protocol-Version': '1',
        },
      });
      if (!res.ok) throw new Error('Failed to load diagram for route');
      return (await res.json()) as DiagramLayout;
    },
    enabled: !!application && !!routeId && !!environment,
  });
}
