import { useQuery } from "@tanstack/react-query";
import {
  fetchMyTeetersList,
  fetchSignatureList,
  fetchSignaturePresigned,
  fetchTeeterPresigned,
  fetchTeetersList,
} from "@/record-management/services/api/signatureAndTeeterService";
import { UploadedTeeter } from "../Settings/uploadTeeterandSingature";

export const useSignatureListWithPresigned = (employeeId: string) => {
  return useQuery({
    queryKey: ["signatureListWithPresigned", employeeId],
    queryFn: async () => {
      const meta = await fetchSignatureList(employeeId);

      const current = meta.items.find(
        (s) => s.isCurrent && s.uploadedSuccessfully,
      );
      let presigned: string | null = null;

      if (current?.id) {
        const res = await fetchSignaturePresigned(current.id);
        presigned = res.presigned;
      }

      return {
        ...meta,
        presignedSignatureUrl: presigned,
        signatureId: current?.id ?? null,
      };
    },
    enabled: !!employeeId,
    staleTime: 0,
    refetchOnMount: true,
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
  });
};

export const useTeetersListWithPresigned = (locale?: string) => {
  return useQuery({
    queryKey: ["teetersListWithPresigned", locale ?? ""],
    queryFn: async () => {
      const meta = await fetchMyTeetersList();

      // Keep stamps that match the requested locale OR have no locale set.
      // This gives the dropdown: locale-specific stamps + universal (null) stamps.
      const current = meta.items.filter(
        (t) =>
          t.uploadedSuccessfully &&
          t.isCurrent &&
          (!locale || !t.locale || t.locale === locale),
      );
      const presignedTeeters: UploadedTeeter[] = await Promise.all(
        current.map(async (item) => {
          const { presigned } = await fetchTeeterPresigned(item.id);
          return {
            id: item.id,
            url: presigned,
            name: item?.name.en,
            locale: item.locale,
          };
        }),
      );

      return {
        ...meta,
        presignedTeeters,
      };
    },
    staleTime: 0,
    refetchOnMount: true,
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
  });
};
