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

export type UpdateWarehouseInput = {
  id: string;
  name?: string;
  storageCondition?: string | null;
  capacity?: number | null;
};
/**
 * Function: updateWarehouse
 *
 * Modifies the mutable fields of an existing warehouse, including name,
 * storageCondition, and capacity. The siteId is immutable after creation.
 */
export async function run(db: Transaction, input: UpdateWarehouseInput, _ctx: CommandContext) {
  const { id, name, storageCondition, capacity } = input;

  // 1. Check warehouse exists
  const warehouse = await db
    .selectFrom("Warehouse")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!warehouse) {
    return err(new WarehouseNotFoundError(id));
  }

  // 2. If name is changing, check uniqueness within site
  if (name !== undefined && name !== warehouse.name) {
    const duplicate = await db
      .selectFrom("Warehouse")
      .selectAll()
      .where("name", "=", name)
      .where("siteId", "=", warehouse.siteId)
      .where("id", "!=", id)
      .forUpdate()
      .executeTakeFirst();

    if (duplicate) {
      return err(new DuplicateWarehouseNameError(name));
    }
  }

  // 3. Build update set
  const updates: Record<string, unknown> = { updatedAt: new Date() };
  if (name !== undefined) updates.name = name;
  if (storageCondition !== undefined) updates.storageCondition = storageCondition;
  if (capacity !== undefined) updates.capacity = capacity;

  // 4. Update warehouse
  const updatedWarehouse = await db
    .updateTable("Warehouse")
    .set(updates)
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ warehouse: updatedWarehouse });
}
