export interface UpdatedTimeRange {
  updatedFrom?: string;
  updatedTo?: string;
}

export interface UpdatedTimeRangeResult {
  query: UpdatedTimeRange;
  error: string | null;
}

function parseLocalDateTime(value: string): Date | null {
  if (!value) return null;
  const parsed = new Date(value);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}

export function toUpdatedTimeRange(
  localFrom: string,
  localTo: string,
): UpdatedTimeRangeResult {
  const from = parseLocalDateTime(localFrom);
  const to = parseLocalDateTime(localTo);

  if (localFrom && !from) {
    return { query: {}, error: "“更新时间从”不是有效时间" };
  }
  if (localTo && !to) {
    return { query: {}, error: "“更新时间至”不是有效时间" };
  }
  if (from && to && from.getTime() > to.getTime()) {
    return { query: {}, error: "更新时间从不能晚于更新时间至" };
  }

  const query: UpdatedTimeRange = {};
  if (from) query.updatedFrom = from.toISOString();
  if (to) query.updatedTo = to.toISOString();
  return { query, error: null };
}
