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

export interface AssignSerialNumberInput {
  serialNumber: string;
  itemId: string;
  storageLocationId: string;
}

/**
 * Function: assignSerialNumber
 *
 * Assigns a unique serial number to an individual unit at goods receipt or
 * production completion. The serial number is created in AVAILABLE state.
 */
export async function run(
  db: Transaction,
  input: AssignSerialNumberInput,
  ctx: CommandContext,
  itemManagementQueries: Pick<ItemManagementQueries, "getItem">,
) {
  const { serialNumber, itemId, storageLocationId } = 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. Check serial number unique per item
  const existingSerial = await db
    .selectFrom("SerialNumber")
    .selectAll()
    .where("serialNumber", "=", serialNumber)
    .where("itemId", "=", itemId)
    .forUpdate()
    .executeTakeFirst();

  if (existingSerial) {
    return err(new DuplicateSerialNumberError(serialNumber));
  }

  // 4. Create serial number in AVAILABLE state
  const serial = await db
    .insertInto("SerialNumber")
    .values({
      serialNumber,
      itemId,
      storageLocationId,
      status: "AVAILABLE",
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ serialNumber: serial });
}
