import type { Transaction } from "../generated/kysely-tailordb";
import {
  ProductionOrderNotFoundError,
  ProductionOrderNotClosableError,
  OpenWorkRemainsError,
  CostSummaryNotSettledError,
} from "../lib/errors.generated";
import { ok, err, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CloseProductionOrderInput {
  id: string;
  from?: string[];
}

/**
 * Function: closeProductionOrder
 *
 * Performs the final administrative close after technical completion and
 * downstream cost settlement are done. The command is the last lifecycle
 * step for the production order.
 */
export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CloseProductionOrderInput & CF,
  _ctx: CommandContext,
) {
  const { id, from, ...customFields } = input;
  void customFields;

  const allowedStatuses = from ?? ["TECHNICALLY_COMPLETE"];

  // 1. Fetch production order with lock
  const order = await db
    .selectFrom("ProductionOrder")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!order) {
    return err(new ProductionOrderNotFoundError(id));
  }

  // 2. Validate status is closable
  if (!allowedStatuses.includes(order.status)) {
    return err(new ProductionOrderNotClosableError(id));
  }

  // 3. Check all work orders are resolved (COMPLETE or CANCELLED)
  const workOrders = await db
    .selectFrom("WorkOrder")
    .selectAll()
    .where("productionOrderId", "=", id)
    .execute();

  const hasOpenWork = workOrders.some(
    (wo) => wo.status !== "COMPLETE" && wo.status !== "CANCELLED",
  );

  if (hasOpenWork) {
    return err(new OpenWorkRemainsError(id));
  }

  // 4. Check cost summary is SETTLED
  const costSummary = await db
    .selectFrom("ManufacturingCostSummary")
    .selectAll()
    .where("productionOrderId", "=", id)
    .executeTakeFirst();

  if (costSummary?.status !== "SETTLED") {
    return err(new CostSummaryNotSettledError(id));
  }

  // 5. Set order status to CLOSED
  const closedOrder = await db
    .updateTable("ProductionOrder")
    .set({
      status: "CLOSED",
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productionOrder: closedOrder });
}
