import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  createCodeDetail,
  deleteCodeDetail,
  getCodeDetailInfo,
  getCodeDetailTree,
  updateCodeDetail,
} from "@/lib/api/commonCode";
import { queryKeys } from "@/lib/queryKeys";
import type { CodeDetailFilter } from "@/lib/schemas/commonCode";

/**
 * 그룹의 전체 디테일 트리 조회 (평탄화 리스트, depth+sort_order 정렬)
 *
 * BE 가 트리를 평탄화해서 한 번에 내려주므로 페이징 없음.
 * 평탄화 리스트 + parent_detail_id 로 FE 에서 트리 indentation 처리.
 */
export function useCodeDetailTree(codeInfo: string | undefined, filters?: CodeDetailFilter) {
  return useQuery({
    queryKey: queryKeys.codeDetail.tree(codeInfo || "", filters),
    queryFn: () =>
      getCodeDetailTree({
        code_info: codeInfo!,
        search: filters?.search,
        is_active: filters?.active,
      }),
    enabled: !!codeInfo,
    select: (data) => data.data || [],
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * 디테일 단건
 */
export function useCodeDetailInfo(codeDetailId: number | string | undefined) {
  return useQuery({
    queryKey: queryKeys.codeDetail.detail(codeDetailId ?? ""),
    queryFn: () => getCodeDetailInfo(codeDetailId!),
    enabled: codeDetailId !== undefined && codeDetailId !== null && codeDetailId !== "",
    select: (data) => data.data,
  });
}

/**
 * 디테일 생성
 */
export function useCreateCodeDetail() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: Record<string, any>) => createCodeDetail(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.codeDetail.all });
    },
    onError: (error) => {
      console.error("디테일 생성 실패:", error);
    },
  });
}

/**
 * 디테일 수정
 */
export function useUpdateCodeDetail() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({
      codeDetailId,
      data,
    }: {
      codeDetailId: number | string;
      data: Record<string, any>;
    }) => updateCodeDetail(codeDetailId, data),
    onSuccess: (_, variables) => {
      qc.invalidateQueries({
        queryKey: queryKeys.codeDetail.detail(variables.codeDetailId),
      });
      qc.invalidateQueries({ queryKey: queryKeys.codeDetail.all });
    },
    onError: (error) => {
      console.error("디테일 수정 실패:", error);
    },
  });
}

/**
 * 디테일 삭제 (CASCADE)
 */
export function useDeleteCodeDetail() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (codeDetailId: number | string) => deleteCodeDetail(codeDetailId),
    onSuccess: (_, codeDetailId) => {
      qc.invalidateQueries({ queryKey: queryKeys.codeDetail.all });
      qc.removeQueries({ queryKey: queryKeys.codeDetail.detail(codeDetailId) });
    },
    onError: (error) => {
      console.error("디테일 삭제 실패:", error);
    },
  });
}
