import { useAuth } from 'hooks/useAuth';
import { useClient } from 'hooks/useClient';
import { useQuery, useQueryClient } from '@tanstack/react-query';

export type AppManifest = {
  slug: string;
  name: string;
  version: string;
  icon: string;
  description: string;
  sourceProject: string;
  commitHash: string;
  publishedAt: string;
  buildDir: string;
};

const QUERY_KEY = ['USER_APPS'] as const;

export function useUserApps() {
  const client = useClient();
  const queryClient = useQueryClient();
  const { user, isAuthenticated } = useAuth();

  const { data: apps = [], isLoading } = useQuery<AppManifest[]>({
    queryKey: QUERY_KEY,
    enabled: isAuthenticated,
    queryFn: () => client.get<{ apps: AppManifest[] }>('/apps').then((r) => r.apps),
    staleTime: 30_000,
  });

  const refetch = () => queryClient.invalidateQueries({ queryKey: QUERY_KEY });

  return { apps, isLoading, refetch, email: user?.email ?? '' };
}
