/**
 * AI 配置 Hooks
 *
 * contract §2.4：aiProviders / updateAiProvider / aiUsage
 */
import { useCallback } from "react";
import { useGraphMutation, useGraphQuery } from "./use-graphql";
import {
  AI_PROVIDERS_QUERY,
  UPDATE_AI_PROVIDER_MUTATION,
  AI_USAGE_QUERY,
} from "@/lib/graphql-client";
import type {
  AiProviderViewModel,
  AiUsageViewModel,
} from "@/types/view-models";

interface AiProvidersResponse {
  aiProviders: AiProviderViewModel[];
}

interface UpdateAiProviderResponse {
  updateAiProvider: { id: string; isActive: boolean };
}

interface AiUsageResponse {
  aiUsage: AiUsageViewModel;
}

export function useAiProviders() {
  const result = useGraphQuery<AiProvidersResponse>(AI_PROVIDERS_QUERY);
  return {
    ...result,
    data: result.data?.aiProviders ?? null,
  };
}

export function useUpdateAiProvider() {
  const [run, state] = useGraphMutation<
    UpdateAiProviderResponse,
    { id: string; input: { isActive: boolean } }
  >(UPDATE_AI_PROVIDER_MUTATION);
  const update = useCallback(
    async (id: string, input: { isActive: boolean }) => {
      const res = await run({ id, input });
      return res.data?.updateAiProvider ?? null;
    },
    [run],
  );
  return [update, state] as const;
}

export function useAiUsage() {
  const result = useGraphQuery<AiUsageResponse>(AI_USAGE_QUERY);
  return {
    ...result,
    data: result.data?.aiUsage ?? null,
  };
}
