"use server";

import prisma from "@/lib/prisma";

export async function getJustifiedImages() {
  const images = await prisma.portfolioImage.findMany({
    where: {
      variants: {
        some: { type: "thumbnail" },
      },
    },
    include: {
      variants: true,
      colors: { include: { color: true } },
    },
  });

  return images
    .map((img) => {
      const variant = img.variants.find((v) => v.type === "thumbnail");
      if (!variant || !variant.width || !variant.height) return null;

      const bg = img.colors.find((c) => c.type === "vibrant")?.color.hex ?? "#e5e7eb";

      return {
        id: img.id,
        fileKey: img.fileKey,
        altText: img.altText ?? img.name ?? "",
        backgroundColor: bg,
        width: variant.width,
        height: variant.height,
        url: variant.url ?? `/api/image/thumbnail/${img.fileKey}.webp`,
      };
    })
    .filter(Boolean) as JustifiedInputImage[];
}

export interface JustifiedInputImage {
  id: string;
  url: string;
  altText: string;
  backgroundColor: string;
  width: number;
  height: number;
}