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

export interface ReserveStockInput {
  itemId: string;
  storageLocationId: string;
  quantity: number;
}

export interface ItemManagementQueries {
  getItem: (
    db: Transaction,
    input: { id: string },
    ctx: CommandContext,
  ) => Promise<{ ok: true; value: { item: { id: string } | null } }>;
}

/**
 * Function: reserveStock
 *
 * Reserves a quantity of stock at a specific item-location pair,
 * reducing the available quantity. Reserved stock remains on-hand
 * but is earmarked for a specific purpose.
 */
export async function run(
  db: Transaction,
  input: ReserveStockInput,
  _ctx: CommandContext,
  itemManagementQueries?: Pick<ItemManagementQueries, "getItem">,
) {
  const { itemId, storageLocationId, quantity } = input;

  // 1. Validate item exists
  const { item } = (await itemManagementQueries!.getItem(db, { id: itemId }, _ctx)).value;

  if (!item) {
    return err(new ItemNotFoundError(itemId));
  }

  // 2. Validate storage location exists
  const location = await db
    .selectFrom("StorageLocation")
    .selectAll()
    .where("id", "=", storageLocationId)
    .executeTakeFirst();

  if (!location) {
    return err(new StorageLocationNotFoundError(storageLocationId));
  }

  // 3. Find stock level for item-location pair (forUpdate for write)
  const stockLevel = await db
    .selectFrom("StockLevel")
    .selectAll()
    .where("itemId", "=", itemId)
    .where("storageLocationId", "=", storageLocationId)
    .forUpdate()
    .executeTakeFirst();

  if (!stockLevel) {
    return err(new StockLevelNotFoundError(`${itemId}:${storageLocationId}`));
  }

  // 4. Check available stock (onHand - reserved - blocked) >= requested quantity
  const available = stockLevel.onHand - stockLevel.reserved - stockLevel.blocked;
  if (available < quantity) {
    return err(new InsufficientAvailableStockError(`${itemId}:${storageLocationId}`));
  }

  // 5. Increment reserved quantity
  const updatedStockLevel = await db
    .updateTable("StockLevel")
    .set({
      reserved: stockLevel.reserved + quantity,
      updatedAt: new Date(),
    })
    .where("id", "=", stockLevel.id)
    .returningAll()
    .executeTakeFirst();

  return ok({ stockLevel: updatedStockLevel! });
}
