<?php

namespace App\Support;

final class SelectOptionFormatter
{
    public static function label(?string $name, ?string $code = null): string
    {
        $name = trim((string) $name);
        $code = trim((string) ($code ?? ''));

        if ($name === '') {
            return $code;
        }

        if ($code === '') {
            return $name;
        }

        return "{$name} ({$code})";
    }

    /**
     * @return list<array{value: string, label: string}>
     */
    public static function pair(int|string $id, string $label): array
    {
        return [[
            'value' => (string) $id,
            'label' => $label,
        ]];
    }

    /**
     * @param  iterable<object>  $rows
     * @return list<array{value: string, label: string}>
     */
    public static function mapRows(
        iterable $rows,
        string $nameKey,
        ?string $codeKey = null,
        string $idKey = 'id',
    ): array {
        $options = [];

        foreach ($rows as $row) {
            $code = $codeKey !== null ? ($row->{$codeKey} ?? null) : null;
            $options[] = [
                'value' => (string) $row->{$idKey},
                'label' => self::label((string) ($row->{$nameKey} ?? ''), $code),
            ];
        }

        return $options;
    }
}
