import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import { shipmentLifecycle } from "../db/shipment.lifecycle.generated";
import type { Transaction } from "../generated/kysely-tailordb";
import { deriveSalesOrderStatus } from "../lib/domain";
import {
  InvalidShipmentStatusError,
  OverShipmentNotAllowedError,
  ShipmentNotFoundError,
} from "../lib/errors.generated";

export interface PostShipmentInput {
  shipmentId: string;
}

export async function run(db: Transaction, input: PostShipmentInput, ctx: CommandContext) {
  void ctx;
  const shipment = await db
    .selectFrom("Shipment")
    .selectAll()
    .where("id", "=", input.shipmentId)
    .forUpdate()
    .executeTakeFirst();
  if (!shipment) {
    return err(new ShipmentNotFoundError(input.shipmentId));
  }
  const nextStatus = shipmentLifecycle.tryTransition(shipment.status, "post");
  if (!nextStatus) {
    return err(new InvalidShipmentStatusError(input.shipmentId));
  }
  const lines = await db
    .selectFrom("ShipmentLine")
    .selectAll()
    .where("shipmentId", "=", input.shipmentId)
    .execute();
  for (const line of lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .forUpdate()
      .executeTakeFirst();
    if (!orderLine || orderLine.quantity - orderLine.shippedQuantity < line.quantity) {
      return err(new OverShipmentNotAllowedError(line.salesOrderLineId));
    }
    await db
      .updateTable("SalesOrderLine")
      .set({
        shippedQuantity: orderLine.shippedQuantity + line.quantity,
      })
      .where("id", "=", orderLine.id)
      .executeTakeFirst();
  }
  const orderLines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", shipment.salesOrderId)
    .execute();
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", shipment.salesOrderId)
    .executeTakeFirstOrThrow();
  const nextOrderStatus = deriveSalesOrderStatus(salesOrder.status, orderLines);
  await db
    .updateTable("SalesOrder")
    .set({ status: nextOrderStatus })
    .where("id", "=", shipment.salesOrderId)
    .executeTakeFirst();
  const updated = await db
    .updateTable("Shipment")
    .set({
      status: nextStatus,
    })
    .where("id", "=", input.shipmentId)
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ shipment: updated });
}
