/**
 * Settings hooks: tag → Paperclip company mappings.
 */

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "./client";

export type PaperclipCompany = {
  id: string;
  name: string;
  prefix: string;
};

export type TagMapping = {
  id: string;
  tag: string;
  tag_label: string;
  company_id: string;
  company_name: string;
  created_at: string;
};

export function usePaperclipCompanies() {
  return useQuery({
    queryKey: ["settings", "paperclip-companies"] as const,
    queryFn: ({ signal }) =>
      apiRequest<PaperclipCompany[]>("/api/settings/paperclip-companies", { signal }),
    staleTime: 60_000,
  });
}

export function useTagMappings() {
  return useQuery({
    queryKey: ["settings", "tag-mappings"] as const,
    queryFn: ({ signal }) =>
      apiRequest<TagMapping[]>("/api/settings/tag-mappings", { signal }),
    staleTime: 10_000,
  });
}

export function useAddTagMapping() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: { tag: string; tag_label: string; company_id: string; company_name: string }) =>
      apiRequest<TagMapping>("/api/settings/tag-mappings", { method: "POST", body }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings", "tag-mappings"] }),
  });
}

export function useDeleteTagMapping() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ ok: boolean }>(`/api/settings/tag-mappings/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["settings", "tag-mappings"] }),
  });
}
