import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidOrderStatusError, SalesOrderNotFoundError } from "../lib/errors.generated";
import { summarizeOrderProgress } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface ReleaseSalesOrderCreditHoldInput {
  salesOrderId: string;
}

export async function run(
  db: Transaction,
  input: ReleaseSalesOrderCreditHoldInput,
  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));
  }
  if (salesOrder.status !== "CREDIT_HOLD") {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const lines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId)
    .execute();
  const { totalOrdered, totalShipped, totalInvoiced } = summarizeOrderProgress(lines);
  const restoredStatus =
    totalOrdered > 0 && totalInvoiced >= totalOrdered
      ? "INVOICED"
      : totalInvoiced > 0
        ? "PARTIALLY_INVOICED"
        : totalOrdered > 0 && totalShipped >= totalOrdered
          ? "SHIPPED"
          : totalShipped > 0
            ? "PARTIALLY_SHIPPED"
            : "CONFIRMED";
  const updated = await db
    .updateTable("SalesOrder")
    .set({ status: restoredStatus, holdReason: null, updatedAt: new Date() })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesOrder: updated! });
}
