import type {
  InventoryLotDetailResponse,
  SaveStockTakeRecordRequest,
} from "@/app/api/stockTake/actions";
import { validateStockTakeQtyString } from "@/app/utils/formatUtil";

export type PickerRecordInputs = Record<
  number,
  {
    firstQty: string;
    secondQty: string;
    firstBadQty: string;
    secondBadQty: string;
    remark: string;
  }
>;

export type BuildPickerBatchSaveResult =
  | { ok: true; records: SaveStockTakeRecordRequest[] }
  | { ok: false; message: string };

/**
 * 从当前列表 + 输入框构建拣货员批量保存请求（与单行 Save 相同 qty 计算规则）。
 */
export function buildPickerBatchSaveRequests(
  details: InventoryLotDetailResponse[],
  recordInputs: PickerRecordInputs,
  isSubmitDisabled: (detail: InventoryLotDetailResponse) => boolean
): BuildPickerBatchSaveResult {
  const records: SaveStockTakeRecordRequest[] = [];

  for (const detail of details) {
    if (isSubmitDisabled(detail)) continue;

    const inputs = recordInputs[detail.id];
    const isFirstSubmit = detail.firstStockTakeQty == null;
    const isSecondSubmit =
      detail.firstStockTakeQty != null && detail.secondStockTakeQty == null;

    if (!isFirstSubmit && !isSecondSubmit) continue;

    const totalQtyStr = isFirstSubmit
      ? inputs?.firstQty
      : inputs?.secondQty;
    const badQtyStr = isFirstSubmit
      ? inputs?.firstBadQty
      : inputs?.secondBadQty;

    if (!totalQtyStr || totalQtyStr.trim() === "") continue;

    const totalValidated = validateStockTakeQtyString(totalQtyStr);
    if (!totalValidated.ok) {
      return { ok: false, message: totalValidated.errorKey };
    }
    const badValidated = validateStockTakeQtyString(badQtyStr, { allowEmpty: true });
    if (!badValidated.ok) {
      return { ok: false, message: badValidated.errorKey };
    }

    const totalQty = totalValidated.qty;
    const badQty = badValidated.qty;

    const availableQty = totalQty - badQty;
    if (availableQty < 0) {
      return { ok: false, message: "Available QTY cannot be negative" };
    }
    const availableValidated = validateStockTakeQtyString(String(availableQty));
    if (!availableValidated.ok) {
      return { ok: false, message: availableValidated.errorKey };
    }

    records.push({
      stockTakeRecordId: detail.stockTakeRecordId ?? null,
      inventoryLotLineId: detail.id,
      qty: availableQty,
      badQty,
      remark: isSecondSubmit ? (inputs?.remark?.trim() || null) : null,
    });
  }

  return { ok: true, records };
}
