"use client";

import { useQuery, useQueryClient } from "@tanstack/react-query";

/** A portfolio Tag as returned by GET /api/portfolio/[id]/tags (ADR-0013). */
export interface Tag {
  id: string;
  name: string;
  colour: string;
  propertyCount: number;
}

/** Shared query key so every tag surface (settings, table, filter) stays in sync. */
export function portfolioTagsKey(portfolioId: string) {
  return ["portfolio-tags", portfolioId] as const;
}

export async function fetchTags(portfolioId: string): Promise<Tag[]> {
  const res = await fetch(`/api/portfolio/${portfolioId}/tags`);
  if (!res.ok) throw new Error("Failed to load tags");
  return res.json();
}

/**
 * The portfolio's Tags, deduped across every component that reads them (chips,
 * assign popover, filter, run UI) via a shared query key. TanStack v4 — reads
 * with `isLoading`.
 */
export function usePortfolioTags(portfolioId: string) {
  return useQuery({
    queryKey: portfolioTagsKey(portfolioId),
    queryFn: () => fetchTags(portfolioId),
    refetchOnWindowFocus: false,
    staleTime: 60_000,
  });
}

/** Invalidate the tags list + the property table so freshly-assigned chips show. */
export function useInvalidateTagSurfaces(portfolioId: string) {
  const queryClient = useQueryClient();
  return () => {
    queryClient.invalidateQueries({ queryKey: portfolioTagsKey(portfolioId) });
    queryClient.invalidateQueries({ queryKey: ["properties", portfolioId] });
  };
}
