import type { Transaction } from "../generated/kysely-tailordb";
import {
  BillingPolicyViolationError,
  DueScheduleNotComputableError,
  InvalidInvoiceStatusError,
  SalesInvoiceNotFoundError,
} from "../lib/errors.generated";
import {
  buildPaymentTermSnapshot,
  calculateDueSchedule,
  decodeJson,
  encodeJson,
  type PaymentTermScheduleLineInput,
} from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface IssueSalesInvoiceInput {
  salesInvoiceId: string;
}

export async function run(db: Transaction, input: IssueSalesInvoiceInput, ctx: CommandContext) {
  void ctx;
  const salesInvoice = await db
    .selectFrom("SalesInvoice")
    .selectAll()
    .where("id", "=", input.salesInvoiceId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesInvoice) {
    return err(new SalesInvoiceNotFoundError(input.salesInvoiceId));
  }
  if (salesInvoice.status !== "DRAFT") {
    return err(new InvalidInvoiceStatusError(input.salesInvoiceId));
  }
  if (!salesInvoice.paymentTermId) {
    return err(new DueScheduleNotComputableError(input.salesInvoiceId));
  }
  const lines = await db
    .selectFrom("SalesInvoiceLine")
    .selectAll()
    .where("salesInvoiceId", "=", input.salesInvoiceId)
    .execute();
  for (const line of lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .forUpdate()
      .executeTakeFirst();
    if (!orderLine) {
      return err(new BillingPolicyViolationError(line.salesOrderLineId));
    }
    if (line.shipmentLineId || line.billingPolicy === "SHIPMENT") {
      if (!line.shipmentLineId) {
        return err(new BillingPolicyViolationError(line.salesOrderLineId));
      }
      const shipmentLine = await db
        .selectFrom("ShipmentLine")
        .selectAll()
        .where("id", "=", line.shipmentLineId)
        .executeTakeFirst();
      if (!shipmentLine || line.quantity > shipmentLine.quantity) {
        return err(new BillingPolicyViolationError(line.salesOrderLineId));
      }
    } else if (line.quantity > orderLine.quantity - orderLine.invoicedQuantity) {
      return err(new BillingPolicyViolationError(line.salesOrderLineId));
    }
    if (line.unitPrice !== orderLine.unitPrice) {
      return err(new BillingPolicyViolationError(line.salesOrderLineId));
    }
  }
  const paymentTerm = await db
    .selectFrom("SalesPaymentTerm")
    .selectAll()
    .where("id", "=", salesInvoice.paymentTermId)
    .executeTakeFirst();
  if (!paymentTerm) {
    return err(new DueScheduleNotComputableError(input.salesInvoiceId));
  }
  const paymentTermSnapshot = encodeJson(buildPaymentTermSnapshot(paymentTerm));
  const dueSchedule =
    calculateDueSchedule(
      decodeJson<PaymentTermScheduleLineInput[]>(paymentTerm.scheduleLines, []),
      salesInvoice.invoiceDate,
      lines.reduce((sum, line) => sum + line.quantity * line.unitPrice, 0),
    ) ?? [];
  if (!dueSchedule.length) {
    return err(new DueScheduleNotComputableError(input.salesInvoiceId));
  }
  for (const line of lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .executeTakeFirst();
    await db
      .updateTable("SalesOrderLine")
      .set({ invoicedQuantity: orderLine!.invoicedQuantity + line.quantity, updatedAt: new Date() })
      .where("id", "=", line.salesOrderLineId)
      .executeTakeFirst();
  }
  const updated = await db
    .updateTable("SalesInvoice")
    .set({
      status: "ISSUED",
      invoiceNumber: salesInvoice.invoiceNumber ?? `INV-${salesInvoice.id}`,
      paymentTermSnapshot,
      dueSchedule: encodeJson(dueSchedule),
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesInvoiceId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesInvoice: updated! });
}
