'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 || 'CATEGORY';
  let n = 2;
  while (await prisma.category.findUnique({ where: { slug } })) {
    slug = `${base}_${n}`;
    n += 1;
  }
  return slug;
}

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

  const showOnPersonalised = String(formData.get('showOnPersonalised') ?? '') === '1';
  const showOnProducts = String(formData.get('showOnProducts') ?? '') === '1';

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

  await prisma.category.create({ data: { name, slug, showOnPersonalised, showOnProducts } });

  redirect('/admin/categories');
}

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

  const showOnPersonalised = String(formData.get('showOnPersonalised') ?? '') === '1';
  const showOnProducts = String(formData.get('showOnProducts') ?? '') === '1';

  await prisma.category.update({ where: { id }, data: { showOnPersonalised, showOnProducts } });
  redirect('/admin/categories');
}

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

  const category = await prisma.category.findUnique({ where: { id } });
  if (!category) return;

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

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