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 {
  InvalidOrderStatusError,
  OrderNotClosableError,
  SalesOrderNotFoundError,
} from "../lib/errors.generated";

export interface CloseSalesOrderInput {
  salesOrderId: string;
  closeReason?: string;
}

export async function run(db: Transaction, input: CloseSalesOrderInput, 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, "close");
  if (!nextStatus) {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const lines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId)
    .execute();
  if (
    lines.some(
      (line) => line.shippedQuantity < line.quantity || line.invoicedQuantity < line.quantity,
    )
  ) {
    return err(new OrderNotClosableError(input.salesOrderId));
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({
      status: nextStatus,
      closeReason: input.closeReason ?? null,
    })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesOrder: updated });
}
