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

export interface RejectCountLineInput {
  countLineId: string;
  recount?: boolean;
}

/**
 * Function: rejectCountLine
 *
 * Rejects a count line, optionally requesting a recount.
 * The line transitions to REJECTED (terminal) or RECOUNT (allows re-recording).
 */
export async function run(db: Transaction, input: RejectCountLineInput, _ctx: CommandContext) {
  const { countLineId, recount = false } = input;

  // 1. Fetch count line
  const countLine = await db
    .selectFrom("InventoryCountLine")
    .selectAll()
    .where("id", "=", countLineId)
    .forUpdate()
    .executeTakeFirst();

  if (!countLine) {
    return err(new CountLineNotFoundError(countLineId));
  }

  // 2. Validate status
  if (countLine.status !== "PENDING") {
    return err(new CountLineNotPendingError(countLineId));
  }

  // 3. Update status
  const newStatus = recount ? "RECOUNT" : "REJECTED";

  const updatedLine = await db
    .updateTable("InventoryCountLine")
    .set({
      status: newStatus,
      updatedAt: new Date(),
    })
    .where("id", "=", countLineId)
    .returningAll()
    .executeTakeFirst();

  return ok({ countLine: updatedLine! });
}
