import {
  HeaderFooterResponseDto,
  headerFooterService,
} from "@/user-management/services/api/headerFooterService";
import { useQuery } from "@tanstack/react-query";

export const useHeaderFooterPresigned = (
  unitId: string,
  positionId?: string,
  recordTypeKey?: string,
) => {
  return useQuery({
    queryKey: ["headers-footers", unitId, positionId, recordTypeKey],
    queryFn: async () => {
      const [headerListRes, footerListRes] = await Promise.all([
        headerFooterService.getHeadersByUnitId(
          unitId,
          positionId,
          recordTypeKey,
        ),
        headerFooterService.getFootersByUnitId(
          unitId,
          positionId,
          recordTypeKey,
        ),
      ]);

      // Only fetch presigned URLs for files that are both active and uploaded
      const activeHeaders = headerListRes.data.items.filter(
        (item) => item.isCurrent && item.uploadedSuccessfully,
      );
      const activeFooters = footerListRes.data.items.filter(
        (item) => item.isCurrent && item.uploadedSuccessfully,
      );

      const withPresigned = async (
        items: HeaderFooterResponseDto[],
        type: "header" | "footer",
      ) =>
        Promise.all(
          items.map(async (item) => {
            try {
              const detail =
                type === "header"
                  ? await headerFooterService.getHeaderById(item.id)
                  : await headerFooterService.getFooterById(item.id);
              return { ...item, presigned: detail.data.presigned };
            } catch {
              return item;
            }
          }),
        );

      const headersWithPresigned = await withPresigned(activeHeaders, "header");
      const footersWithPresigned = await withPresigned(activeFooters, "footer");

      return { headers: headersWithPresigned, footers: footersWithPresigned };
    },
    enabled: !!unitId,
    staleTime: 10 * 60 * 1000, // 10 minutes
  });
};
