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

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));
  }
  if (shipment.status !== "DRAFT") {
    return err(new InvalidShipmentStatusError(input.shipmentId));
  }
  const lines = await db
    .selectFrom("ShipmentLine")
    .selectAll()
    .where("shipmentId", "=", input.shipmentId)
    .execute();
  const handoff = [];
  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,
        updatedAt: new Date(),
      })
      .where("id", "=", orderLine.id)
      .executeTakeFirst();
    if (line.requiresInventoryHandoff) {
      handoff.push({
        shipmentLineId: line.id,
        salesOrderLineId: line.salesOrderLineId,
        quantity: line.quantity,
      });
    }
  }
  const orderLines = await db
    .selectFrom("SalesOrderLine")
    .selectAll()
    .where("salesOrderId", "=", shipment.salesOrderId)
    .execute();
  const nextOrderStatus = deriveSalesOrderStatus(
    (await db
      .selectFrom("SalesOrder")
      .selectAll()
      .where("id", "=", shipment.salesOrderId)
      .executeTakeFirst())!.status,
    orderLines,
  );
  await db
    .updateTable("SalesOrder")
    .set({ status: nextOrderStatus, updatedAt: new Date() })
    .where("id", "=", shipment.salesOrderId)
    .executeTakeFirst();
  const updated = await db
    .updateTable("Shipment")
    .set({
      status: "POSTED",
      inventoryHandoff: handoff.length ? encodeJson(handoff) : null,
      updatedAt: new Date(),
    })
    .where("id", "=", input.shipmentId)
    .returningAll()
    .executeTakeFirst();
  return ok({ shipment: updated! });
}
