<?php

namespace App\Support;

use Illuminate\Support\Collection;

final class LegacyJson
{
    public static function toArray(mixed $value): array
    {
        if ($value instanceof Collection) {
            return array_values($value->all());
        }

        if (is_array($value)) {
            return array_values($value);
        }

        if ($value === null) {
            return [];
        }

        if (is_string($value)) {
            $trimmed = trim($value);

            if ($trimmed === '') {
                return [];
            }

            $decoded = json_decode($trimmed, true);

            if (json_last_error() === JSON_ERROR_NONE) {
                if (is_array($decoded)) {
                    return array_values($decoded);
                }

                if (is_string($decoded) && $decoded !== $trimmed) {
                    return self::toArray($decoded);
                }

                return $decoded === null || $decoded === ''
                    ? []
                    : [$decoded];
            }

            return [$trimmed];
        }

        return [$value];
    }
}
