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

export interface CloseProductionOrderInput {
  id: 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(db: Transaction, input: CloseProductionOrderInput, _ctx: CommandContext) {
  const { id } = input;

  // 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
  const nextStatus = productionOrderLifecycle.tryTransition(order.status, "close");
  if (!nextStatus) {
    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: nextStatus,
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ productionOrder: closedOrder });
}
