"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { generatePoNumber } from "@/lib/utils";
import { revalidatePath } from "next/cache";
import type { ParsedImportLine } from "@/app/api/po/import/route";

export type ImportPoInput = {
  title: string;
  vesselId: string;
  accountId: string;
  vendorId?: string;
  piQuotationNo?: string;
  placeOfDelivery?: string;
  tcDelivery?: string;
  tcDispatch?: string;
  tcInspection?: string;
  tcTransitInsurance?: string;
  tcPaymentTerms?: string;
  tcOthers?: string;
  lineItems: ParsedImportLine[];
};

export async function importPo(
  input: ImportPoInput
): Promise<{ id: string } | { error: string }> {
  const session = await auth();
  if (!session?.user) return { error: "Unauthorized" };
  if (!hasPermission(session.user.role, "create_po") && session.user.role !== "ADMIN") {
    return { error: "You do not have permission to import purchase orders." };
  }

  const total = input.lineItems.reduce(
    (sum, item) => sum + item.quantity * item.unitPrice * (1 + (item.gstRate ?? 0.18)),
    0
  );

  const po = await db.purchaseOrder.create({
    data: {
      poNumber: generatePoNumber(),
      title: input.title,
      status: "DRAFT",
      totalAmount: total,
      currency: "INR",
      vesselId: input.vesselId,
      accountId: input.accountId,
      vendorId: input.vendorId ?? null,
      piQuotationNo: input.piQuotationNo ?? null,
      placeOfDelivery: input.placeOfDelivery ?? null,
      tcDelivery: input.tcDelivery ?? null,
      tcDispatch: input.tcDispatch ?? null,
      tcInspection: input.tcInspection ?? null,
      tcTransitInsurance: input.tcTransitInsurance ?? null,
      tcPaymentTerms: input.tcPaymentTerms ?? null,
      tcOthers: input.tcOthers ?? null,
      submitterId: session.user.id,
      lineItems: {
        create: input.lineItems.map((item, idx) => ({
          name: item.name,
          quantity: item.quantity,
          unit: item.unit,
          unitPrice: item.unitPrice,
          totalPrice: item.quantity * item.unitPrice,
          gstRate: item.gstRate ?? 0.18,
          sortOrder: idx,
        })),
      },
      actions: {
        create: { actionType: "CREATED", actorId: session.user.id },
      },
    },
  });

  revalidatePath("/my-orders");
  revalidatePath("/dashboard");
  return { id: po.id };
}
