"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { canPerformAction } from "@/lib/po-state-machine";
import { notify } from "@/lib/notifier";
import { revalidatePath } from "next/cache";

export async function confirmReceipt({
  poId,
  notes,
}: {
  poId: string;
  notes?: string;
}): Promise<{ ok: true } | { error: string }> {
  const session = await auth();
  if (!session?.user) return { error: "Unauthorized" };

  const po = await db.purchaseOrder.findUnique({
    where: { id: poId },
    include: {
      submitter: true,
      lineItems: true,
      vessel: { include: { site: true } },
    },
  });
  if (!po) return { error: "PO not found" };
  if (!canPerformAction(po.status, "confirm_receipt", session.user.role)) {
    return { error: "You cannot confirm receipt on this PO." };
  }

  await db.purchaseOrder.update({
    where: { id: poId },
    data: {
      status: "CLOSED",
      closedAt: new Date(),
      receipt: notes ? { create: { storageKey: "", fileName: "no-file", notes } } : undefined,
      actions: {
        create: { actionType: "RECEIPT_CONFIRMED", actorId: session.user.id, note: notes ?? null },
      },
    },
  });

  // Auto-update inventory: use PO siteId, fall back to vessel's home site
  const siteId = (po as typeof po & { siteId?: string | null }).siteId ?? po.vessel?.site?.id ?? null;
  if (siteId) {
    for (const li of po.lineItems) {
      if (!li.productId) continue;
      const qty = Number(li.quantity);
      await db.itemInventory.upsert({
        where: { productId_siteId: { productId: li.productId, siteId } },
        update: { quantity: { increment: qty } },
        create: { productId: li.productId, siteId, quantity: qty },
      });
    }
    revalidatePath(`/admin/sites/${siteId}`);
  }

  const [managers, accounts] = await Promise.all([
    db.user.findMany({ where: { role: "MANAGER", isActive: true } }),
    db.user.findMany({ where: { role: "ACCOUNTS", isActive: true } }),
  ]);
  await notify({ event: "RECEIPT_CONFIRMED", po, recipients: [...managers, ...accounts] });

  revalidatePath(`/po/${poId}`);
  revalidatePath("/dashboard");
  return { ok: true };
}
