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

export interface CreateShipmentInput {
  companyId: string;
  salesOrderId: string;
  shipFromSiteId?: string | null;
  shipmentDate?: Date;
  trackingNumber?: string | null;
  shippingAddressSnapshot?: Record<string, unknown> | null;
  lines: ShipmentLineInput[];
}

export async function run(db: Transaction, input: CreateShipmentInput, ctx: CommandContext) {
  void ctx;
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", input.salesOrderId)
    .executeTakeFirst();
  if (!salesOrder) {
    return err(new SalesOrderNotFoundError(input.salesOrderId));
  }
  if (
    !["CONFIRMED", "PARTIALLY_SHIPPED", "PARTIALLY_INVOICED", "SHIPPED"].includes(salesOrder.status)
  ) {
    return err(new OrderNotShippableError(input.salesOrderId));
  }
  if (!input.lines.length) {
    return err(new InvalidShipmentLineError(input.salesOrderId));
  }
  for (const line of input.lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .executeTakeFirst();
    if (!orderLine || line.quantity <= 0 || orderLine.salesOrderId !== input.salesOrderId) {
      return err(new InvalidShipmentLineError(line.salesOrderLineId));
    }
    if (orderLine.quantity - orderLine.shippedQuantity < line.quantity) {
      return err(new OrderNotShippableError(line.salesOrderLineId));
    }
  }
  const shipment = await db
    .insertInto("Shipment")
    .values({
      companyId: input.companyId,
      salesOrderId: input.salesOrderId,
      customerId: salesOrder.customerId,
      shipFromSiteId: input.shipFromSiteId ?? null,
      shipmentDate: input.shipmentDate ?? new Date(),
      status: "DRAFT",
      trackingNumber: input.trackingNumber ?? null,
      shippingAddressSnapshot: input.shippingAddressSnapshot
        ? encodeJson(input.shippingAddressSnapshot)
        : salesOrder.shippingAddressSnapshot,
      inventoryHandoff: null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();
  for (const line of input.lines) {
    await db
      .insertInto("ShipmentLine")
      .values({
        shipmentId: shipment!.id,
        salesOrderLineId: line.salesOrderLineId,
        quantity: line.quantity,
        unitId: line.unitId ?? null,
        trackingReference: line.trackingReference ?? null,
        requiresInventoryHandoff: line.requiresInventoryHandoff ?? true,
        createdAt: new Date(),
        updatedAt: null,
      })
      .executeTakeFirst();
  }
  return ok({ shipment: shipment! });
}
