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

export interface CreateLotInput {
  lotNumber: string;
  itemId: string;
  manufactureDate?: Date | null;
  expirationDate?: Date | null;
  supplierLotReference?: string | null;
}

/**
 * Function: createLot
 *
 * Creates a new lot/batch record for a lot-tracked item.
 * Each lot is uniquely identified by its lot number within a specific item.
 */
export async function run(
  db: Transaction,
  input: CreateLotInput,
  ctx: CommandContext,
  itemManagementQueries: Pick<ItemManagementQueries, "getItem">,
) {
  const { lotNumber, itemId, manufactureDate, expirationDate, supplierLotReference } = input;

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

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

  // 2. Check lotNumber unique per item
  const existingLot = await db
    .selectFrom("Lot")
    .selectAll()
    .where("lotNumber", "=", lotNumber)
    .where("itemId", "=", itemId)
    .forUpdate()
    .executeTakeFirst();

  if (existingLot) {
    return err(new DuplicateLotNumberError(lotNumber));
  }

  // 3. Create lot
  const lot = await db
    .insertInto("Lot")
    .values({
      lotNumber,
      itemId,
      manufactureDate: manufactureDate ?? null,
      expirationDate: expirationDate ?? null,
      supplierLotReference: supplierLotReference ?? null,
      status: "ACTIVE",
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ lot });
}
