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

export interface ShipmentHeaderInput {
  companyId: string;
  salesOrderId: string;
  shipFromSiteId?: string | null;
  shipmentDate?: Date;
  trackingNumber?: string | null;
  shippingAddressSnapshot?: Record<string, unknown> | null;
}

export interface CreateShipmentInput {
  header: ShipmentHeaderInput;
  lines: ShipmentLineInput[];
}

export async function run<CF extends Record<string, unknown>, LCF extends Record<string, unknown>>(
  db: Transaction,
  input: {
    header: ShipmentHeaderInput & CF;
    lines: (ShipmentLineInput & LCF)[];
  },
  ctx: CommandContext,
) {
  void ctx;
  const { header, lines } = input;
  const salesOrder = await db
    .selectFrom("SalesOrder")
    .selectAll()
    .where("id", "=", header.salesOrderId)
    .executeTakeFirst();
  if (!salesOrder) {
    return err(new SalesOrderNotFoundError(header.salesOrderId));
  }
  if (
    !["CONFIRMED", "PARTIALLY_SHIPPED", "PARTIALLY_INVOICED", "SHIPPED"].includes(salesOrder.status)
  ) {
    return err(new OrderNotShippableError(header.salesOrderId));
  }
  if (!lines.length) {
    return err(new InvalidShipmentLineError(header.salesOrderId));
  }
  for (const line of lines) {
    const orderLine = await db
      .selectFrom("SalesOrderLine")
      .selectAll()
      .where("id", "=", line.salesOrderLineId)
      .executeTakeFirst();
    if (!orderLine || line.quantity <= 0 || orderLine.salesOrderId !== header.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({
      // Header input first (incl. custom fields) so command-set columns always win.
      ...(header as Record<string, unknown>),
      companyId: header.companyId,
      salesOrderId: header.salesOrderId,
      customerId: salesOrder.customerId,
      shipFromSiteId: header.shipFromSiteId ?? null,
      shipmentDate: header.shipmentDate ?? new Date(),
      status: "DRAFT",
      trackingNumber: header.trackingNumber ?? null,
      shippingAddressSnapshot: header.shippingAddressSnapshot
        ? encodeJson(header.shippingAddressSnapshot)
        : salesOrder.shippingAddressSnapshot,
    })
    .returningAll()
    .executeTakeFirstOrThrow();
  if (lines.length > 0) {
    await db
      .insertInto("ShipmentLine")
      .values(
        lines.map((line) => {
          const { salesOrderLineId, quantity, unitId, trackingReference, ...lineCustomFields } =
            line;
          return {
            // Custom fields first so command-set columns always win.
            ...(lineCustomFields as Record<string, unknown>),
            shipmentId: shipment.id,
            salesOrderLineId,
            quantity,
            unitId: unitId ?? null,
            trackingReference: trackingReference ?? null,
          };
        }),
      )
      .execute();
  }
  return ok({ shipment });
}
