<?php

namespace App\Support;

/**
 * Normalizes serial input from UI payloads before it ever reaches a service.
 *
 * Two shapes exist in the wild: raw serial *numbers* typed into a GRN
 * (comma/newline-separated text) and serial *ids* picked from a serialized
 * lot in checkout / damage / transfer forms. Both must be cleaned identically
 * everywhere they are read, or a trailing comma ("SN-1, SN-2,") silently
 * counts three rows where two are created.
 */
final class SerialInput
{
    /**
     * Split raw text (or an array) into serial numbers: trim whitespace,
     * drop blanks, reindex.
     *
     * @return array<int, string>
     */
    public static function numbers(mixed $raw): array
    {
        $parts = is_array($raw) ? $raw : preg_split('/[\s,;]+/', (string) $raw);

        return array_values(array_filter(
            array_map(fn (mixed $part): string => trim((string) $part), $parts ?? []),
            fn (string $part): bool => $part !== '',
        ));
    }

    /**
     * Coerce a payload of serial ids to a deduplicated list of positive ints.
     *
     * @return array<int, int>
     */
    public static function ids(mixed $raw): array
    {
        $parts = is_array($raw) ? $raw : preg_split('/[\s,;]+/', (string) $raw);

        return array_values(array_unique(array_filter(
            array_map(fn (mixed $id): int => (int) $id, $parts ?? []),
            fn (int $id): bool => $id > 0,
        )));
    }
}
