import { isNumber } from "es-toolkit";

const DURATION_REGEX = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/;

const SIZE_REGEX = /^(\d+(?:\.\d+)?)(B|KB|MB|GB)$/;

export function parseDuration(value: string): number {
  const match = DURATION_REGEX.exec(value);
  if (!match) {
    throw new Error(`无效的时长格式: "${value}"，支持格式如 "30s"、"5m"、"2h"、"7d"、"500ms"`);
  }

  const num = parseFloat(match[1]!);
  const unit = match[2]!;

  const multipliers: Record<string, number> = { d: 86400000, h: 3600000, m: 60000, ms: 1, s: 1000 };
  const durationMs = num * multipliers[unit]!;
  if (!Number.isInteger(durationMs) || durationMs <= 0 || !Number.isFinite(durationMs)) {
    throw new Error(`无效的时长格式: "${value}"，解析结果必须为正整数毫秒`);
  }
  return durationMs;
}

export function parseSize(value: number | string): number {
  if (isNumber(value)) {
    if (!Number.isInteger(value) || value < 0 || !Number.isSafeInteger(value)) {
      throw new Error(`无效的 size 数值: ${value}，必须为非负安全整数`);
    }
    return value;
  }

  const match = SIZE_REGEX.exec(value);
  if (!match) {
    throw new Error(`无效的 size 格式: "${value}"，支持格式如 "100MB"、"512KB"、"1GB"、"1024B"`);
  }

  const num = parseFloat(match[1]!);
  const unit = match[2]!;

  const bytes =
    unit === "B" ? num : unit === "KB" ? num * 1024 : unit === "MB" ? num * 1024 * 1024 : num * 1024 * 1024 * 1024;
  if (!Number.isInteger(bytes) || bytes < 0 || !Number.isSafeInteger(bytes)) {
    throw new Error(`无效的 size 数值: ${value}，必须解析为非负安全整数字节数`);
  }
  return bytes;
}
