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

import { aiFeedbackService } from "@/services/ai-feedback.service";
import type {
  AIFeedbackStatus,
  AIFeedbackSubjectType,
  AIFeedbackSubmitInput,
} from "@/types/ai-feedback";

const KEY_ROOT = ["ai", "feedback"] as const;

export function useAIFeedbackSummary(
  subjectType: AIFeedbackSubjectType | undefined,
  subjectId: number | undefined,
) {
  return useQuery({
    enabled: !!subjectType && !!subjectId,
    queryKey: [...KEY_ROOT, "summary", subjectType, subjectId] as const,
    queryFn: () =>
      aiFeedbackService.summary(
        subjectType as AIFeedbackSubjectType,
        subjectId as number,
      ),
  });
}

export function useSubmitAIFeedback() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (input: AIFeedbackSubmitInput) => aiFeedbackService.submit(input),
    onSuccess: (_res, vars) => {
      qc.invalidateQueries({
        queryKey: [...KEY_ROOT, "summary", vars.subject_type, vars.subject_id],
      });
      qc.invalidateQueries({ queryKey: [...KEY_ROOT, "list"] });
    },
  });
}

export function useAIFeedbackList(
  params: {
    status?: AIFeedbackStatus;
    rating?: "up" | "down";
    subject_type?: AIFeedbackSubjectType;
    prompt_key?: string;
    page?: number;
    size?: number;
  } = {},
) {
  return useQuery({
    queryKey: [...KEY_ROOT, "list", params] as const,
    queryFn: () => aiFeedbackService.list(params),
  });
}

export function useResolveAIFeedback() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      id,
      status,
      notes,
    }: {
      id: number;
      status: Exclude<AIFeedbackStatus, "open">;
      notes?: string;
    }) => aiFeedbackService.resolve(id, status, notes),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY_ROOT }),
  });
}
