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

export interface SubmitSalesOrderInput {
  salesOrderId: string;
}

export async function run(db: Transaction, input: SubmitSalesOrderInput, 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 !== "DRAFT") {
    return err(new InvalidOrderStatusError(input.salesOrderId));
  }
  const lines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", input.salesOrderId)
    .execute();
  if (!lines.length) {
    return err(new EmptyOrderNotAllowedError(input.salesOrderId));
  }
  if (
    lines.some((line) => line.requiresPhysicalFulfillment) &&
    !salesOrder.shippingAddressSnapshot
  ) {
    return err(new ShippingAddressRequiredError(input.salesOrderId));
  }
  const updated = await db
    .updateTable("SalesOrder")
    .set({ status: "SUBMITTED", updatedAt: new Date() })
    .where("id", "=", input.salesOrderId)
    .returningAll()
    .executeTakeFirst();
  return ok({ salesOrder: updated! });
}
