<?php

declare(strict_types=1);

namespace App\Support;

use Filament\Schemas\Components\Utilities\Set;

/**
 * 单据备注在上下游之间的默认传递规则。
 */
final class DberpDocumentRemarkPropagation
{
    public static function trimmedOrNull(?string $remark): ?string
    {
        $trimmed = trim((string) ($remark ?? ''));

        return $trimmed !== '' ? $trimmed : null;
    }

    public static function applyLineRemark(Set $set, ?string $remark): void
    {
        $set('remark', self::trimmedOrNull($remark));
    }

    /**
     * @param  list<string|null>  $parts
     */
    public static function merge(?string ...$parts): ?string
    {
        $pieces = [];

        foreach ($parts as $part) {
            $normalized = self::trimmedOrNull($part);

            if ($normalized !== null && ! in_array($normalized, $pieces, true)) {
                $pieces[] = $normalized;
            }
        }

        return $pieces !== [] ? implode('；', $pieces) : null;
    }

    /**
     * 转单头备注：弹窗输入优先，否则继承上游单据备注，再否则使用系统默认文案。
     */
    public static function resolveConversionHeaderRemark(?string $overrideRemark, ?string $sourceRemark, string $fallback): string
    {
        $override = self::trimmedOrNull($overrideRemark);

        if ($override !== null) {
            return $override;
        }

        $source = self::trimmedOrNull($sourceRemark);

        if ($source !== null) {
            return $source;
        }

        return $fallback;
    }
}
