/**
 * Normalize an incoming `roleIds` value into a number[].
 *
 * Handles all the shapes the field can arrive in:
 * - JSON body: a real array ([1, 2]) or a single number.
 * - multipart/form-data: a JSON string ("[1,2]"), a comma-separated string
 *   ("1,2"), a single value, or repeated fields (parsed by the framework into
 *   an array of strings).
 *
 * Invalid entries are dropped to NaN so class-validator's @IsInt/@IsPositive
 * can reject them with a clear message.
 */
export function parseRoleIds(value: unknown): unknown {
  if (value === undefined || value === null || value === '') {
    return undefined;
  }

  const toNumbers = (items: unknown[]): number[] =>
    items
      .map((item) => (typeof item === 'string' ? item.trim() : item))
      .filter((item) => item !== '' && item !== null && item !== undefined)
      .map((item) => Number(item));

  if (Array.isArray(value)) {
    return toNumbers(value);
  }

  if (typeof value === 'number') {
    return [value];
  }

  if (typeof value === 'string') {
    const trimmed = value.trim();

    if (trimmed.startsWith('[')) {
      try {
        const parsed: unknown = JSON.parse(trimmed);
        if (Array.isArray(parsed)) {
          return toNumbers(parsed);
        }
      } catch {
        // fall through to comma-splitting
      }
    }

    return toNumbers(trimmed.split(','));
  }

  return value;
}
