import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { salesOrderLifecycle } from "../db/salesOrder.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CancellationBlockedError,
  InvalidOrderStatusError,
  SalesOrderNotFoundError,
} from "../lib/errors.generated";

export interface CancelSalesOrderInput {
  salesOrderId: string;
}

export async function run(db: Transaction, input: CancelSalesOrderInput, ctx: CommandContext) {
  void ctx;
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", input.salesOrderId)
    .forUpdate()
    .executeTakeFirst();
  if (!salesOrder) {
    return err(new SalesOrderNotFoundError(input.salesOrderId));
  }
  const nextStatus = salesOrderLifecycle.tryTransition(salesOrder.status, "cancel");
  if (!nextStatus) {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const [shipments, invoices] = await Promise.all([
    db.selectFrom("Shipment").selectAll().where("salesOrderId", "=", input.salesOrderId).execute(),
    db
      .selectFrom("SalesInvoice")
      .selectAll()
      .where("salesOrderId", "=", input.salesOrderId)
      .execute(),
  ]);
  if (
    shipments.some((shipment) => shipment.status === "POSTED") ||
    invoices.some((invoice) => ["ISSUED", "SENT"].includes(invoice.status))
  ) {
    return err(new CancellationBlockedError(input.salesOrderId));
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({ status: nextStatus })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesOrder: updated });
}
