'use server';

import { redirect } from 'next/navigation';
import { prisma } from '@/lib/prisma';

function slugify(input: string) {
  return input
    .toUpperCase()
    .trim()
    .replace(/[^A-Z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '');
}

async function uniqueSlug(base: string) {
  let slug = base || 'COLLECTION';
  let n = 2;
  while (await prisma.collection.findUnique({ where: { slug } })) {
    slug = `${base}_${n}`;
    n += 1;
  }
  return slug;
}

export async function createCollection(formData: FormData) {
  const name = String(formData.get('name') ?? '').trim();
  if (!name) throw new Error('Name is required.');

  const group = String(formData.get('group') ?? '');
  if (group !== 'OCCASION' && group !== 'RECIPIENT') {
    throw new Error('Choose Occasion or Recipient.');
  }

  const slug = await uniqueSlug(slugify(name));

  await prisma.collection.create({ data: { name, slug, group } });

  redirect('/admin/collections');
}

export async function deleteCollection(formData: FormData) {
  const id = String(formData.get('id') ?? '');
  if (!id) return;

  const inUse = await prisma.product.count({ where: { collections: { some: { id } } } });
  if (inUse > 0) {
    redirect('/admin/collections?error=in_use');
  }

  await prisma.collection.delete({ where: { id } });
  redirect('/admin/collections');
}
