import { connectDB } from "@/lib/db";
import { ClientPhotoFolder } from "@/models/ClientPhotoFolder";
import { PhotoRating } from "@/models/PhotoRating";
import { PhotoMetadata } from "@/models/PhotoMetadata";
import { Client } from "@/models/Client";
import { listFolderImages } from "@/lib/nextcloud";
import { ensurePhotoDimensions, computePrintFormatLabel } from "@/lib/photoFormat";

// Extrahiert aus admin/folders/[folderId]/page.tsx.
export async function getPhotoFolderDetail(folderId: string) {
  await connectDB();
  const folder = await ClientPhotoFolder.findById(folderId).lean();
  if (!folder) return null;

  const [client, images, ratings, metadataDocs] = await Promise.all([
    Client.findById(folder.clientId).lean(),
    listFolderImages(folder.nextcloudPath).catch(() => []),
    PhotoRating.find({ folderId }).lean(),
    PhotoMetadata.find({ folderId }).lean(),
  ]);
  const ratingByFile = new Map(ratings.map((r) => [r.fileName, r]));
  const metaByFile = new Map(metadataDocs.map((m) => [m.fileName, m]));

  // Pixelmaße fehlender Fotos parallel nachziehen+cachen (erster Seitenaufruf
  // je Foto etwas langsamer, danach kommt alles aus PhotoMetadata) - siehe
  // lib/photoFormat.ts.
  const dimsByFile = new Map(
    await Promise.all(
      images.map(async (fileName) => {
        const existing = metaByFile.get(fileName);
        const dims = await ensurePhotoDimensions(
          String(folder.clientId),
          folderId,
          fileName,
          folder.nextcloudPath,
          existing ? { widthPx: existing.widthPx, heightPx: existing.heightPx } : undefined
        );
        return [fileName, dims] as const;
      })
    )
  );

  return {
    id: String(folder._id),
    label: folder.label,
    nextcloudPath: folder.nextcloudPath,
    released: Boolean(folder.released),
    orderId: folder.orderId ? String(folder.orderId) : null,
    clientId: String(folder.clientId),
    clientName: client?.name || "",
    clientEmail: client?.email || "",
    photos: images.map((fileName) => {
      const dims = dimsByFile.get(fileName);
      return {
        fileName,
        stars: ratingByFile.get(fileName)?.stars ?? 0,
        approved: ratingByFile.get(fileName)?.approvedForDownload ?? false,
        note: ratingByFile.get(fileName)?.note ?? "",
        tags: metaByFile.get(fileName)?.tags ?? [],
        formatLabel:
          dims?.widthPx != null && dims?.heightPx != null ? computePrintFormatLabel(dims.widthPx, dims.heightPx) : null,
      };
    }),
  };
}
