import { TransformFnParams } from 'class-transformer';

const parseArrayInput = (value: unknown): unknown[] | unknown | undefined => {
  if (value === undefined || value === null) {
    return undefined;
  }

  if (Array.isArray(value)) {
    return value.flatMap((item) => {
      const parsed = parseArrayInput(item);
      if (typeof parsed === 'undefined') {
        return [];
      }
      return Array.isArray(parsed) ? parsed : [parsed];
    });
  }

  if (typeof value !== 'string') {
    return value;
  }

  const trimmed = value.trim();
  if (!trimmed) {
    return undefined;
  }

  if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
    try {
      return parseArrayInput(JSON.parse(trimmed));
    } catch {
      return [trimmed];
    }
  }

  if (trimmed.includes(',')) {
    return trimmed
      .split(',')
      .map((part) => part.trim())
      .filter(Boolean);
  }

  return [trimmed];
};

export const toStringArray = ({ value }: TransformFnParams): string[] | unknown | undefined => {
  const parsed = parseArrayInput(value);
  if (typeof parsed === 'undefined') {
    return undefined;
  }

  if (!Array.isArray(parsed)) {
    return parsed;
  }

  return parsed.map((item) => String(item).trim()).filter(Boolean);
};

export const toNumberArray = ({ value }: TransformFnParams): number[] | unknown | undefined => {
  const parsed = parseArrayInput(value);
  if (typeof parsed === 'undefined') {
    return undefined;
  }

  if (!Array.isArray(parsed)) {
    return parsed;
  }

  return parsed.map((item) => Number(item));
};
