/**
 * Hooks for Convex data access.
 */

import { useQuery, useMutation } from "convex/react";
import { api } from "../../convex/_generated/api";
import { useHashCache } from "../context";
import { useEffect } from "react";
import type { CardHashEntry } from "../recognition";
import type { Id } from "../../convex/_generated/dataModel";

type User = { _id: Id<"users"> } | null | undefined;

/**
 * Hook to get the current authenticated user.
 * Returns unauthenticated state when auth is not configured.
 */
export function useCurrentUser(): { user: User; isLoading: boolean; isAuthenticated: boolean } {
  // When using ConvexProvider (no auth), just return unauthenticated state
  // Switch to ConvexAuthProvider + useConvexAuth when Zitadel is configured
  return {
    user: null,
    isLoading: false,
    isAuthenticated: false,
  };
}

/**
 * Hook to fetch and cache card hashes from Convex.
 */
export function useCardHashes() {
  const { setCardHashes, hashesLoaded, lastHashSync, cardHashes } = useHashCache();
  
  // Fetch all cards from Convex
  const cards = useQuery(api.cards.list);
  
  useEffect(() => {
    if (cards) {
      // Convert Convex cards to CardHashEntry format
      const entries: CardHashEntry[] = cards.map((card) => ({
        id: card.scryfallId,
        name: card.name,
        setCode: card.setCode,
        collectorNumber: card.collectorNumber,
        imageUri: card.imageUri,
        hash: new Uint8Array(card.hash),
      }));
      
      setCardHashes(entries);
    }
  }, [cards, setCardHashes]);
  
  return {
    loading: cards === undefined && !hashesLoaded,
    loaded: hashesLoaded,
    count: cardHashes.length,
    lastSync: lastHashSync,
    hashes: cardHashes,
  };
}

/**
 * Hook to get card count.
 */
export function useCardCount() {
  const count = useQuery(api.cards.count);
  return count ?? 0;
}

/**
 * Hook to search cards by name.
 */
export function useSearchCards(query: string) {
  const results = useQuery(
    api.cards.searchByName,
    query.length >= 2 ? { name: query } : "skip"
  );
  return results ?? [];
}

/**
 * Hook to manage collection.
 */
export function useCollection(userId?: string) {
  const collection = useQuery(
    api.collections.getByUser,
    userId ? { userId: userId as any } : "skip"
  );
  
  const addCard = useMutation(api.collections.add);
  const removeCard = useMutation(api.collections.remove);
  const updateQuantity = useMutation(api.collections.updateQuantity);
  
  return {
    collection: collection ?? [],
    addCard,
    removeCard,
    updateQuantity,
    loading: collection === undefined,
  };
}
