'use server'

import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { hashPassword } from "@/lib/auth";

const updateSchema = z.object({
  plan: z.enum(["trial", "starter", "standard", "premium"]),
  status: z.enum(["active", "suspended", "expired"]),
});

export async function updateSubscription(establishmentId: string, formData: FormData) {
  const plan = formData.get("plan") as string;
  const status = formData.get("status") as string;

  const parsed = updateSchema.safeParse({ plan, status });
  if (!parsed.success) {
    throw new Error("Données invalides");
  }

  await prisma.subscription.update({
    where: { establishmentId },
    data: {
      plan: parsed.data.plan,
      status: parsed.data.status,
    },
  });

  revalidatePath(`/superadmin/establishments/${establishmentId}`);
}

export async function deleteEstablishment(establishmentId: string) {
  await prisma.establishment.delete({
    where: { id: establishmentId },
  });
  redirect("/superadmin/establishments");
}

const createAdminSchema = z.object({
  email: z.string().email("Email invalide"),
  password: z.string().min(8, "Le mot de passe doit contenir au moins 8 caractères"),
});

export async function createAdmin(establishmentId: string, formData: FormData) {
  const email = formData.get("email") as string;
  const password = formData.get("password") as string;

  const parsed = createAdminSchema.safeParse({ email, password });
  if (!parsed.success) {
    throw new Error(parsed.error.issues.map((e) => e.message).join(", "));
  }

  const existing = await prisma.user.findUnique({ where: { email: parsed.data.email } });
  if (existing) throw new Error("Cet email est déjà utilisé");

  const hashed = await hashPassword(parsed.data.password);

  await prisma.user.create({
    data: {
      email: parsed.data.email,
      password: hashed,
      role: "admin",
      establishmentId,
    },
  });

  revalidatePath(`/superadmin/establishments/${establishmentId}`);
}

export async function deleteAdmin(establishmentId: string, userId: string) {
  await prisma.user.deleteMany({
    where: { id: userId, establishmentId, role: "admin" },
  });

  revalidatePath(`/superadmin/establishments/${establishmentId}`);
}
