// hooks/useGetRemarks.ts
// dto/IncomingRecords/remark.dto.ts

export interface LocalizedNameDto {
  am: string;
  en: string;
}

export interface RemarkEmployeeDto {
  id: string;
  name: LocalizedNameDto;
}

export interface RemarkCommentorDto {
  id: string;
  employee: RemarkEmployeeDto;
}

export interface IncomingRemarkDto {
  createdAt: string;
  updatedAt: string;
  id: string;

  incomingInstanceId: string;

  commentorId: string;
  delegateCommenterId: string | null;

  comment: string;

  commentor: RemarkCommentorDto;

  delegateCommenter: RemarkCommentorDto | null;
}

export interface IncomingRemarkResponseDto {
  count: number;
  items: IncomingRemarkDto[];
}
import { getRemarksByIncomingInstanceId } from "@/record-management/services/api/incomingRecordService";
import { useQueries, useQuery } from "@tanstack/react-query";

export const useGetRemarks = (
  incomingInstanceId: string,
  enabled: boolean = true,
) => {
  const { data, isLoading, isError, error, refetch, isFetching } = useQuery({
    queryKey: ["incoming-remarks", incomingInstanceId],
    queryFn: () => getRemarksByIncomingInstanceId(incomingInstanceId),
    enabled: !!incomingInstanceId && enabled,
    staleTime: 0,
  });

  return {
    remarks: data,
    isLoadingRemarks: isLoading,
    isFetchingRemarks: isFetching,
    isRemarksError: isError,
    remarksError: error,
    refetchRemarks: refetch,
  };
};

export const useGetMergedRemarks = (instanceIds: string[]) => {
  const results = useQueries({
    queries: instanceIds.map((id) => ({
      queryKey: ["incoming-remarks", id],
      queryFn: () => getRemarksByIncomingInstanceId(id),
      enabled: !!id,
      staleTime: 0,
    })),
  });

  const isLoading = results.some((r) => r.isLoading);
  const isError = results.some((r) => r.isError);
  const mergedItems = results
    .flatMap((r) => r.data?.items ?? [])
    .sort(
      (a, b) =>
        new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
    );

  return { mergedItems, isLoading, isError };
};
