"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { requirePermission } from "@/lib/permissions";

const CUSTOMERS_BASE = "/iv-manage-84x2/customers";

export async function createCustomerGroup(formData: FormData) {
  await requirePermission("customers", "add");
  const name = String(formData.get("name") ?? "").trim();
  if (!name) redirect(`${CUSTOMERS_BASE}/groups?error=Name+is+required`);

  await prisma.customerGroup.create({ data: { name } });
  revalidatePath(`${CUSTOMERS_BASE}/groups`);
  revalidatePath(CUSTOMERS_BASE);
  redirect(`${CUSTOMERS_BASE}/groups?success=Customer+group+added.`);
}

export async function deleteCustomerGroup(id: string) {
  await requirePermission("customers", "delete");
  await prisma.customerGroup.delete({ where: { id } });
  revalidatePath(`${CUSTOMERS_BASE}/groups`);
  revalidatePath(CUSTOMERS_BASE);
  redirect(`${CUSTOMERS_BASE}/groups?success=Customer+group+deleted.`);
}

export async function updateCustomerGroup(customerId: string, formData: FormData) {
  await requirePermission("customers", "edit");
  const groupId = String(formData.get("groupId") ?? "").trim() || null;
  await prisma.customer.update({ where: { id: customerId }, data: { groupId } });
  revalidatePath(CUSTOMERS_BASE);
  redirect(`${CUSTOMERS_BASE}?success=Customer+group+updated.`);
}

export async function blockCustomer(customerId: string, formData: FormData) {
  await requirePermission("customers", "edit");
  const reason = String(formData.get("reason") ?? "").trim() || null;
  await prisma.customer.update({ where: { id: customerId }, data: { blocked: true, blockedReason: reason } });
  revalidatePath(CUSTOMERS_BASE);
  revalidatePath(`${CUSTOMERS_BASE}/blocked`);
  redirect(`${CUSTOMERS_BASE}?success=Customer+blocked.`);
}

export async function unblockCustomer(customerId: string) {
  await requirePermission("customers", "edit");
  await prisma.customer.update({ where: { id: customerId }, data: { blocked: false, blockedReason: null } });
  revalidatePath(CUSTOMERS_BASE);
  revalidatePath(`${CUSTOMERS_BASE}/blocked`);
  redirect(`${CUSTOMERS_BASE}/blocked?success=Customer+unblocked.`);
}
