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

export interface SubmitInventoryAdjustmentInput {
  id: string;
}

/**
 * Function: submitInventoryAdjustment
 *
 * Submits an inventory adjustment for approval, transitioning it from DRAFT to PENDING_APPROVAL status.
 */
export async function run(
  db: Transaction,
  input: SubmitInventoryAdjustmentInput,
  _ctx: CommandContext,
) {
  const { id } = input;

  // 1. Fetch adjustment
  const adjustment = await db
    .selectFrom("InventoryAdjustment")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!adjustment) {
    return err(new AdjustmentNotFoundError(id));
  }

  // 2. Validate status is DRAFT
  if (adjustment.status !== "DRAFT") {
    return err(new AdjustmentNotDraftError(id));
  }

  // 3. Update status to PENDING_APPROVAL
  const updated = await db
    .updateTable("InventoryAdjustment")
    .set({ status: "PENDING_APPROVAL", updatedAt: new Date() })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ inventoryAdjustment: updated! });
}
