import { CliError } from "./errors.js";

export function parseTime(value: string, option: string): string {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    throw new CliError("CLI 参数错误", "INVALID_TIME", `${option} must be a valid ISO 8601 / RFC 3339 timestamp`, 2);
  }
  if (!/[zZ]|[+-]\d\d:\d\d$/.test(value)) {
    throw new CliError("CLI 参数错误", "TIMEZONE_REQUIRED", `${option} must include an explicit timezone offset`, 2);
  }
  return value;
}

export function addMinutesPreservingOffset(value: string, minutes: number): string {
  const match = value.match(/([+-])(\d\d):(\d\d)$/);
  const end = new Date(new Date(value).getTime() + minutes * 60_000);
  if (!match) return end.toISOString().replace(".000Z", "Z");
  const sign = match[1] === "+" ? 1 : -1;
  const offsetMinutes = sign * (Number(match[2]) * 60 + Number(match[3]));
  const local = new Date(end.getTime() + offsetMinutes * 60_000);
  return `${local.toISOString().replace(".000Z", "")}${match[1]}${match[2]}:${match[3]}`;
}

