import { prisma } from "./prisma";
import { amountInWords } from "./format";
import { unitPriceFor } from "./pricing";

export async function settings() {
  const row = await prisma.companySettings.findUnique({ where: { id: "company" } });
  if (!row) throw new Error("Company settings are missing. Seed the database first.");
  return row;
}

export async function nextDocumentNumber(kind: "proforma" | "delivery") {
  const current = await settings();
  if (kind === "proforma") {
    const number = `${current.proformaPrefix}${String(current.proformaNext).padStart(5, "0")}`;
    await prisma.companySettings.update({
      where: { id: "company" },
      data: { proformaNext: current.proformaNext + 1 },
    });
    return number;
  }
  const number = `${current.deliveryPrefix}${String(current.deliveryNext).padStart(5, "0")}`;
  await prisma.companySettings.update({
    where: { id: "company" },
    data: { deliveryNext: current.deliveryNext + 1 },
  });
  return number;
}

export type TaxOptions = { applyVat?: boolean; applyStamp?: boolean };

export async function computeDocumentTotals(
  lines: Array<{ quantity: number; unitPrice: number }>,
  discount = 0,
  { applyVat = true, applyStamp = true }: TaxOptions = {},
) {
  const company = await settings();
  const subtotal = lines.reduce((sum, line) => sum + line.quantity * line.unitPrice, 0);
  const afterDiscount = Math.max(0, subtotal - discount);
  const vatAmount = applyVat ? afterDiscount * (company.vatRate / 100) : 0;
  const stampAmount = applyStamp ? company.stampAmount : 0;
  const total = afterDiscount + vatAmount + stampAmount;
  return {
    amountBeforeTax: afterDiscount,
    vatAmount,
    stampAmount,
    total,
    totalInWords: amountInWords(total),
    applyVat,
    applyStamp,
  };
}

export async function pricedLines(
  customerAccountType: string,
  items: Array<{ productId: string; quantity: number; unitPrice?: number }>,
) {
  const lines = [];
  for (const item of items) {
    const unitPrice = item.unitPrice ?? (await unitPriceFor(item.productId, customerAccountType, item.quantity));
    lines.push({
      productId: item.productId,
      quantity: item.quantity,
      unitPrice,
      lineAmount: item.quantity * unitPrice,
    });
  }
  return lines;
}
