import { connectDB } from "@/lib/db";
import { ClientPhotoFolder } from "@/models/ClientPhotoFolder";
import { PhotoRating } from "@/models/PhotoRating";
import { Client } from "@/models/Client";
import { listFolderImages } from "@/lib/nextcloud";

// 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] = await Promise.all([
    Client.findById(folder.clientId).lean(),
    listFolderImages(folder.nextcloudPath).catch(() => []),
    PhotoRating.find({ folderId }).lean(),
  ]);
  const ratingByFile = new Map(ratings.map((r) => [r.fileName, r]));

  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) => ({
      fileName,
      stars: ratingByFile.get(fileName)?.stars ?? 0,
      approved: ratingByFile.get(fileName)?.approvedForDownload ?? false,
      note: ratingByFile.get(fileName)?.note ?? "",
    })),
  };
}
