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

export type UpdateLotInput = {
  id: string;
  manufactureDate?: Date | null;
  expirationDate?: Date | null;
  supplierLotReference?: string | null;
};
/**
 * Function: updateLot
 *
 * Updates the mutable fields of a lot record. The lotNumber is immutable
 * after creation and cannot be changed. Cannot update a FULLY_CONSUMED lot.
 */
export async function run(db: Transaction, input: UpdateLotInput, _ctx: CommandContext) {
  const { id, manufactureDate, expirationDate, supplierLotReference } = input;

  // 1. Fetch existing lot
  const existing = await db
    .selectFrom("Lot")
    .selectAll()
    .where("id", "=", id)
    .forUpdate()
    .executeTakeFirst();

  if (!existing) {
    return err(new LotNotFoundError(id));
  }

  // 2. Check status
  if (existing.status === "FULLY_CONSUMED") {
    return err(new LotFullyConsumedError(id));
  }

  // 3. Update mutable fields
  const updated = await db
    .updateTable("Lot")
    .set({
      ...(manufactureDate !== undefined && { manufactureDate }),
      ...(expirationDate !== undefined && { expirationDate }),
      ...(supplierLotReference !== undefined && { supplierLotReference }),
      updatedAt: new Date(),
    })
    .where("id", "=", id)
    .returningAll()
    .executeTakeFirst();

  return ok({ lot: updated! });
}
