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

export interface CreateInventoryCountInput {
  countType: string;
  warehouseId?: string;
  storageLocationId?: string;
  plannedDate: Date;
}

/**
 * Function: createInventoryCount
 *
 * Creates a new inventory count document in PLANNED status.
 * Counts can be FULL (entire warehouse) or CYCLE (specific storage locations).
 */
export async function run(db: Transaction, input: CreateInventoryCountInput, _ctx: CommandContext) {
  const { countType, warehouseId, storageLocationId, plannedDate } = input;

  // 1. Validate countType
  if (countType !== "FULL" && countType !== "CYCLE") {
    return err(new InvalidCountTypeError(countType));
  }

  // 2. Validate location scope
  if (warehouseId) {
    const warehouse = await db
      .selectFrom("Warehouse")
      .selectAll()
      .where("id", "=", warehouseId)
      .executeTakeFirst();

    if (!warehouse) {
      return err(new WarehouseNotFoundError(warehouseId));
    }
  } else if (storageLocationId) {
    const location = await db
      .selectFrom("StorageLocation")
      .selectAll()
      .where("id", "=", storageLocationId)
      .executeTakeFirst();

    if (!location) {
      return err(new StorageLocationNotFoundError(storageLocationId));
    }
  } else {
    return err(new WarehouseNotFoundError("no location scope provided"));
  }

  // 3. Create count in PLANNED status
  const inventoryCount = await db
    .insertInto("InventoryCount")
    .values({
      countType,
      warehouseId: warehouseId ?? null,
      storageLocationId: storageLocationId ?? null,
      plannedDate,
      status: "PLANNED",
      isFrozen: false,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ inventoryCount: inventoryCount! });
}
