import { TemplateService } from "./templateService";
import {
  isFontResourceType,
  isListBulletResourceType,
  ListBulletResource,
} from "@/user-management/TemplateSample/utils/templateResourceConstants";

export const LIST_BULLET_RESOURCES_QUERY_KEY = [
  "listBulletResources",
] as const;

export async function fetchListBulletResources(): Promise<ListBulletResource[]> {
  const typesResponse = await TemplateService.getResourceTypes();
  const types = typesResponse.items || [];

  let bulletTypes = types.filter((type) => isListBulletResourceType(type));
  if (bulletTypes.length === 0) {
    bulletTypes = types.filter((type) => !isFontResourceType(type));
  }

  const grouped = await Promise.all(
    bulletTypes.map(async (type) => {
      const response = await TemplateService.getTemplates({
        resourceTypeId: type.id,
      });
      return (response.items || [])
        .filter((item) => item.id && Boolean(item.presigned))
        .map((item) => ({
          id: item.id,
          name: item.name,
          presigned: item.presigned as string,
          resourceTypeId: type.id,
          fileInfo: item.fileInfo as ListBulletResource["fileInfo"],
        }));
    }),
  );

  return grouped.flat();
}
