import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  createCodeInfo,
  deleteCodeInfo,
  getCodeInfoInfo,
  getCodeInfoList,
  updateCodeInfo,
} from "@/lib/api/commonCode";
import { queryKeys } from "@/lib/queryKeys";
import type { CodeInfoFilter } from "@/lib/schemas/commonCode";

/**
 * 그룹(code_info) 목록 조회
 */
export function useCodeInfoList(filters?: CodeInfoFilter) {
  return useQuery({
    queryKey: queryKeys.codeInfo.list(filters),
    queryFn: () =>
      getCodeInfoList({
        search: filters?.search,
        is_active: filters?.active,
      }),
    select: (data) => data.data || [],
  });
}

/**
 * 그룹 단건 조회
 */
export function useCodeInfoDetail(codeInfo: string | undefined) {
  return useQuery({
    queryKey: queryKeys.codeInfo.detail(codeInfo || ""),
    queryFn: () => getCodeInfoInfo(codeInfo!),
    enabled: !!codeInfo,
    select: (data) => data.data,
  });
}

/**
 * 그룹 생성
 */
export function useCreateCodeInfo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: Record<string, any>) => createCodeInfo(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.codeInfo.all });
    },
    onError: (error) => {
      console.error("그룹 생성 실패:", error);
    },
  });
}

/**
 * 그룹 수정
 */
export function useUpdateCodeInfo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ codeInfo, data }: { codeInfo: string; data: Record<string, any> }) =>
      updateCodeInfo(codeInfo, data),
    onSuccess: (_, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.codeInfo.detail(variables.codeInfo) });
      qc.invalidateQueries({ queryKey: queryKeys.codeInfo.all });
    },
    onError: (error) => {
      console.error("그룹 수정 실패:", error);
    },
  });
}

/**
 * 그룹 삭제 (CASCADE)
 */
export function useDeleteCodeInfo() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (codeInfo: string) => deleteCodeInfo(codeInfo),
    onSuccess: (_, codeInfo) => {
      qc.invalidateQueries({ queryKey: queryKeys.codeInfo.all });
      qc.invalidateQueries({ queryKey: queryKeys.codeDetail.all });
      qc.removeQueries({ queryKey: queryKeys.codeInfo.detail(codeInfo) });
    },
    onError: (error) => {
      console.error("그룹 삭제 실패:", error);
    },
  });
}
