function formatDatePart(date: Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}${month}${day}`;
}

export function createBatchIdCandidate(seq: number, now = new Date()) {
  const datePart = formatDatePart(now);
  const seqPart = String(seq).padStart(3, '0');

  return `CG-${datePart}-${seqPart}`;
}

export async function createUniqueBatchId(
  exists?: (batchId: string) => Promise<boolean>,
  maxAttempts = 999,
) {
  const now = new Date();

  for (let seq = 1; seq <= maxAttempts; seq += 1) {
    const batchId = createBatchIdCandidate(seq, now);

    if (!exists) {
      return batchId;
    }

    if (!(await exists(batchId))) {
      return batchId;
    }
  }

  throw new Error('批次 ID 生成失败，请重试。');
}