// "use server";

// import prisma from "@/lib/prisma";

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

//   return images
//     .map((img) => {
//       const variant = img.variants.find((v) => v.type === "resized");
//       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/resized/${img.fileKey}.webp`,
//       };
//     })
//     .filter(Boolean) as JustifiedInputImage[];
// }

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

"use server"

import prisma from "@/lib/prisma";

export interface JustifiedInputImage {
  id: string;
  url: string;
  altText: string;
  backgroundColor: string;
  width: number;
  height: number;
  fileKey: string;
  fullUrl: string;
  fullWidth: number;
  fullHeight: number;
}

interface Variant {
  type: string;
  url?: string | null;
  width: number;
  height: number;
}

interface Color {
  type: string;
  color: {
    hex: string | null;
  };
}

interface PortfolioImage {
  id: string;
  fileKey: string;
  name?: string | null;
  altText?: string | null;
  variants: Variant[];
  colors: Color[];
}

interface PortfolioImageSortContext {
  image: PortfolioImage;
  group: "highlighted" | "featured" | "default" | string;
  sortOrder: number;
}

// const groupPriority = {
//   highlighted: 0,
//   featured: 1,
//   default: 2,
// } as const;

function shuffleImages<T>(arr: T[]): T[] {
  const shuffled = [...arr];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

// Stub: Replace this with your actual DB or API call
async function getImageSortContext(params: {
  year?: string;
  albumId?: string;
  type: string;
}): Promise<PortfolioImageSortContext[]> {
  const { year, albumId, type } = params;

  const typeEntry = await prisma.portfolioType.findUnique({
  where: { slug: type },
    // select: { id: true },
  });
  if (!typeEntry) return []; 
  const typeId = typeEntry.id;

  const sortContexts = await prisma.portfolioSortContext.findMany({
    where: {
      type: typeId,
      ...(year ? { year: year } : {}),
      ...(albumId ? { albumId } : {}),
      image: {
        // published: true,
      },
    },
    include: {
      image: {
        include: {
          variants: true,
          colors: {
            include: {
              color: true,
            },
          },
        },
      },
    },
  });

  return sortContexts;
}

export async function getJustifiedImages(
  year: string | null | undefined,
  albumId: string | null | undefined,
  type: string,
  shouldShuffle = false
): Promise<JustifiedInputImage[] | null> {
  if (!year && !albumId) return null;

  const sortContexts = await getImageSortContext({
    year: year || undefined,
    albumId: albumId || undefined,
    type,
  });

  // const validImages = sortContexts
  //   .filter((ctx) => ctx.image && ctx.image.variants.some((v) => v.type === "resized"))
  //   .sort((a, b) => {
  //     const groupA = groupPriority[a.group as keyof typeof groupPriority] ?? 3;
  //     const groupB = groupPriority[b.group as keyof typeof groupPriority] ?? 3;
  //     if (groupA !== groupB) return groupA - groupB;
  //     return a.sortOrder - b.sortOrder;
  //   });
  
  type GroupName = "highlighted" | "featured" | "default";

  const grouped: Record<GroupName, PortfolioImageSortContext[]> = {
    highlighted: [],
    featured: [],
    default: [],
  };

  for (const ctx of sortContexts) {
    const rawGroup = ctx.group?.toLowerCase() ?? "default";
    const group = ["highlighted", "featured", "default"].includes(rawGroup)
      ? (rawGroup as GroupName)
      : "default";

    grouped[group].push(ctx);
  }

  const processGroup = (list: PortfolioImageSortContext[]) =>
    shouldShuffle
      ? shuffleImages(list)
      : [...list].sort((a, b) => a.sortOrder - b.sortOrder);

  const finalList = [
    ...processGroup(grouped.highlighted),
    ...processGroup(grouped.featured),
    ...processGroup(grouped.default),
  ];

  const output: JustifiedInputImage[] = [];

  for (const ctx of finalList) {
    const img = ctx.image;
    const variant = img.variants.find((v) => v.type === "resized");
    const full = img.variants.find((v) => v.type === "modified");

    if (!variant || !variant.width || !variant.height) continue;

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

    output.push({
      id: img.id,
      fileKey: img.fileKey,
      altText: img.altText ?? img.name ?? "",
      backgroundColor: bg,
      width: variant.width,
      height: variant.height,
      url: variant.url ?? `/api/image/resized/${img.fileKey}.webp`,
      fullUrl: full?.url ?? `/api/image/modified/${img.fileKey}.webp`,
      fullWidth: full?.width ?? 0,
      fullHeight: full?.height ?? 0,
    });
  }

  return output;
}
