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 { buildPaymentTermSnapshot, encodeJson } from "../lib/domain";
import {
  CustomerNotActiveError,
  InvalidOrderStatusError,
  MissingFinalPriceError,
  SalesOrderNotFoundError,
} from "../lib/errors.generated";
import type { BusinessPartnerQueries } from "../module";

export interface ConfirmSalesOrderInput {
  salesOrderId: string;
}

export async function run(
  db: Transaction,
  input: ConfirmSalesOrderInput,
  ctx: CommandContext,
  businessPartnerQueries: Pick<BusinessPartnerQueries, "getPartner">,
) {
  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, "confirm");
  if (!nextStatus) {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const { partner: customer } = (
    await businessPartnerQueries.getPartner(db, { id: salesOrder.customerId }, ctx)
  ).value;
  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: nextStatus,
      paymentTermSnapshot,
    })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesOrder: updated });
}
