"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { z } from "zod";
import { revalidatePath } from "next/cache";

type ActionResult = { ok: true } | { error: string };

const productSchema = z.object({
  code: z.string().min(1).max(50),
  name: z.string().min(1).max(200),
  description: z.string().optional(),
});

export async function createProduct(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_products")) {
    return { error: "Forbidden" };
  }

  const parsed = productSchema.safeParse({
    code: formData.get("code"),
    name: formData.get("name"),
    description: formData.get("description") || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0].message };

  const existing = await db.product.findUnique({ where: { code: parsed.data.code } });
  if (existing) return { error: "A product with this code already exists." };

  await db.product.create({ data: parsed.data });
  revalidatePath("/admin/products");
  return { ok: true };
}

export async function updateProduct(formData: FormData): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_products")) {
    return { error: "Forbidden" };
  }

  const id = formData.get("id") as string;
  if (!id) return { error: "Product ID required" };

  const parsed = z.object({
    code: z.string().min(1).max(50),
    name: z.string().min(1).max(200),
    description: z.string().optional(),
  }).safeParse({
    code: formData.get("code"),
    name: formData.get("name"),
    description: formData.get("description") || undefined,
  });
  if (!parsed.success) return { error: parsed.error.errors[0].message };

  const conflict = await db.product.findFirst({ where: { code: parsed.data.code, id: { not: id } } });
  if (conflict) return { error: "Another product already uses that code." };

  await db.product.update({ where: { id }, data: parsed.data });
  revalidatePath("/admin/products");
  return { ok: true };
}

export async function deleteProduct(id: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_products")) return { error: "Forbidden" };

  const blocked = await db.pOLineItem.findFirst({
    where: { productId: id, po: { status: { not: "DRAFT" } } },
  });
  if (blocked) return { error: "Cannot delete: item is referenced in submitted or active purchase orders." };

  await db.$transaction(async (tx) => {
    await tx.pOLineItem.updateMany({ where: { productId: id }, data: { productId: null } });
    await tx.itemConsumption.deleteMany({ where: { productId: id } });
    await tx.itemInventory.deleteMany({ where: { productId: id } });
    await tx.productVendorPrice.deleteMany({ where: { productId: id } });
    await tx.product.delete({ where: { id } });
  });

  revalidatePath("/admin/products");
  return { ok: true };
}

export async function toggleProductActive(productId: string): Promise<ActionResult> {
  const session = await auth();
  if (!session?.user || !hasPermission(session.user.role, "manage_products")) {
    return { error: "Forbidden" };
  }

  const product = await db.product.findUnique({ where: { id: productId } });
  if (!product) return { error: "Product not found" };

  await db.product.update({
    where: { id: productId },
    data: { isActive: !product.isActive },
  });
  revalidatePath("/admin/products");
  return { ok: true };
}
