// useSeal.ts
import { useQuery, useQueries, UseQueryResult } from "@tanstack/react-query";

import {
  fetchSeal,
  fetchSealById,
} from "@/record-management/services/api/sealService";
import { useAuthUser } from "@/shared/hooks/useAuthUser";

export interface Seal {
  id: string;
  isCurrent: boolean;
  uploadedSuccessfully: boolean;
  // other seal properties
}

export interface SealDetail {
  id: string;
  name: { am: string; en?: string };
  presigned: string;
  isCurrent: boolean;
  uploadedSuccessfully: boolean;
}

export const useSeal = () => {
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId ?? null;

  const {
    data: sealsData,
    isLoading: isSealsLoading,
    isError: isSealsError,
    refetch,
  } = useQuery<{ items: Seal[] }, Error>({
    queryKey: ["seals", unitId],
    queryFn: () => {
      if (!unitId) {
        throw new Error("Organization unit ID is required");
      }

      return fetchSeal(unitId);
    },
    staleTime: 1000 * 60 * 1,
    enabled: !!unitId, // Only fetch if unitId exists
  });

  // Filter to only include active and successfully uploaded seals
  const activeSeals = (sealsData?.items || []).filter(
    (seal: Seal) => seal.isCurrent && seal.uploadedSuccessfully
  );

  const sealDetailQueries = useQueries({
    queries: activeSeals.map((seal: Seal) => ({
      queryKey: ["sealDetails", seal.id],
      queryFn: () => fetchSealById(seal.id),
      enabled: !!seal.id && !!sealsData?.items,
    })),
  }) as UseQueryResult<SealDetail, Error>[];

  const isLoading =
    isSealsLoading || sealDetailQueries.some((q) => q.isLoading);
  const isError = isSealsError || sealDetailQueries.some((q) => q.isError);

  // Extract successful queries only and filter out deactivated seals
  const sealDetailsData = sealDetailQueries
    .filter(
      (q) =>
        q.isSuccess && q.data && q.data.isCurrent && q.data.uploadedSuccessfully
    )
    .map((q) => q.data);

  return {
    seals: activeSeals,
    sealDetailsData,
    isLoading,
    isError,
    refetch,
  };
};
