<?php
/**
 * Maps a stored request onto one row of the register export.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Core;

/**
 * Headers and values are produced by the same class so the two can never drift
 * apart - an export whose columns do not line up with its header is worse than
 * no export at all when it lands in front of an inspector.
 */
final class RegisterRow
{
    /**
     * @return string[]
     */
    public static function headers(): array
    {
        return [
            'Referință',
            'Transmisă la (UTC)',
            'Nume',
            'Email',
            'Comandă / contract',
            'Tip',
            'Comandă pe firmă',
            'Stare',
            'Termen rambursare (UTC)',
            'Rambursată la (UTC)',
            'Produse',
            'Declarație',
        ];
    }

    /**
     * @param array<string,mixed> $record
     *
     * @return string[]
     */
    public static function from(array $record): array
    {
        return [
            self::text($record, 'reference'),
            self::text($record, 'submitted'),
            self::text($record, 'name'),
            self::text($record, 'email'),
            self::text($record, 'contract_ref'),
            self::text($record, 'type'),
            self::text($record, 'b2b'),
            self::text($record, 'status'),
            self::text($record, 'refund_due'),
            self::text($record, 'settled'),
            self::lines($record),
            self::text($record, 'declaration'),
        ];
    }

    /**
     * @param array<string,mixed> $record
     */
    private static function text(array $record, string $key): string
    {
        $value = isset($record[$key]) ? $record[$key] : '';

        return is_scalar($value) ? (string) $value : '';
    }

    /**
     * @param array<string,mixed> $record
     */
    private static function lines(array $record): string
    {
        $lines = isset($record['lines']) && is_array($record['lines']) ? $record['lines'] : [];
        $parts = [];

        foreach ($lines as $line) {
            if (!is_array($line)) {
                continue;
            }

            $label = (string) (isset($line['name']) ? $line['name'] : '');
            $sku   = (string) (isset($line['sku']) ? $line['sku'] : '');

            if ('' !== trim($sku)) {
                $label .= ' (' . $sku . ')';
            }

            $parts[] = $label . ' x ' . (int) (isset($line['qty']) ? $line['qty'] : 0);
        }

        return implode('; ', $parts);
    }
}
