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

export interface ConfirmSalesOrderInput {
  salesOrderId: string;
}

export async function run(db: Transaction, input: ConfirmSalesOrderInput, 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 !== "SUBMITTED") {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const customer = await db
    .selectFrom("BusinessPartner")
    .selectAll()
    .where("id", "=", salesOrder.customerId)
    .executeTakeFirst();
  if (customer?.status !== "ACTIVE") {
    return err(new CustomerNotActiveError(salesOrder.customerId));
  }
  const lines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId)
    .execute();
  if (lines.some((line) => line.unitPrice <= 0 || !line.currencyId)) {
    return err(new MissingFinalPriceError(input.salesOrderId));
  }
  let paymentTermSnapshot = salesOrder.paymentTermSnapshot;
  if (salesOrder.paymentTermId) {
    const paymentTerm = await db
      .selectFrom("SalesPaymentTerm")
      .selectAll()
      .where("id", "=", salesOrder.paymentTermId)
      .executeTakeFirst();
    if (paymentTerm) {
      paymentTermSnapshot = encodeJson(buildPaymentTermSnapshot(paymentTerm));
    }
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({
      status: "CONFIRMED",
      paymentTermSnapshot,
      updatedAt: new Date(),
    })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesOrder: updated! });
}
