'use server'

import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { z } from "zod";

const schema = z.object({
  name: z.string().min(2, "Le nom doit contenir au moins 2 caractères"),
  slug: z.string().regex(/^[a-z0-9-]+$/, "Le slug ne peut contenir que des minuscules, chiffres et tirets"),
});

export async function createEstablishment(formData: FormData) {
  const name = formData.get("name") as string;
  const slug = formData.get("slug") as string;

  const parsed = schema.safeParse({ name, slug });
  if (!parsed.success) {
    const message = parsed.error.issues.map((e) => e.message).join(", ");
    redirect(`/superadmin/establishments/new?error=${encodeURIComponent(message)}`);
  }

  try {
    await prisma.establishment.create({
      data: {
        name: parsed.data.name,
        slug: parsed.data.slug,
        subscription: {
          create: {
            plan: "trial",
            status: "active",
          },
        },
      },
    });
  } catch {
    redirect(`/superadmin/establishments/new?error=${encodeURIComponent("Ce slug existe déjà ou une erreur est survenue")}`);
  }

  redirect("/superadmin/establishments");
}
