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

// "2019 MI Governor Diwali Function" -> "2019-mi-governor-diwali-function"
export function slugify(input: string): string {
  return input
    .toString()
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, "") // strip anything not alphanumeric/space/hyphen
    .replace(/\s+/g, "-") // spaces -> hyphens
    .replace(/-+/g, "-") // collapse multiple hyphens
    .replace(/^-+|-+$/g, ""); // trim leading/trailing hyphens
}

// Ensures the generated slug is unique in cms_gallery_albums.
// Appends -2, -3, etc. on collision. Pass excludeId when updating an
// existing album so it doesn't collide with itself.
export async function getUniqueAlbumSlug(
  title: string,
  excludeId?: bigint
): Promise<string> {
  const base = slugify(title) || "album";
  let candidate = base;
  let counter = 2;

  while (true) {
    const existing = await prisma.cms_gallery_albums.findFirst({
      where: {
        slug: candidate,
        ...(excludeId ? { id: { not: excludeId } } : {}),
      },
      select: { id: true },
    });

    if (!existing) return candidate;

    candidate = `${base}-${counter}`;
    counter++;
  }
}