<?php

declare(strict_types=1);

namespace App\Support\Print;

use App\Models\DberpSystemProfile;

final class DberpPrintViewSupport
{
    /**
     * @return array{name: string, address: string, phone: string, email: string}
     */
    public static function companyProfile(): array
    {
        $profile = DberpSystemProfile::query()->first();

        $name = filled($profile?->company_name)
            ? (string) $profile->company_name
            : (string) config('dberp.product.name', 'DBErp');

        $addressParts = array_filter([
            filled($profile?->region_name_snapshot) ? (string) $profile->region_name_snapshot : null,
            filled($profile?->address) ? (string) $profile->address : null,
        ]);

        return [
            'name' => $name,
            'address' => implode(' ', $addressParts),
            'phone' => (string) ($profile?->contact_phone ?? ''),
            'email' => (string) ($profile?->contact_email ?? ''),
        ];
    }

    public static function formatSkuSpec(?string $skuCode, ?string $specText): string
    {
        $parts = array_filter([
            filled($skuCode) ? (string) $skuCode : null,
            filled($specText) ? (string) $specText : null,
        ]);

        return $parts !== [] ? implode(' / ', $parts) : '—';
    }

    public static function formatBatchAndSerial(?string $batchNo, mixed $serialNumbers): string
    {
        $segments = [];

        if (filled($batchNo)) {
            $segments[] = (string) __('dberp.fields.batch_no').': '.(string) $batchNo;
        }

        $serialList = self::normalizeSerialNumbers($serialNumbers);
        if ($serialList !== []) {
            $segments[] = implode(', ', $serialList);
        }

        return implode('；', $segments);
    }

    /**
     * @return list<string>
     */
    private static function normalizeSerialNumbers(mixed $serialNumbers): array
    {
        if (! is_array($serialNumbers)) {
            return [];
        }

        $normalized = [];
        foreach ($serialNumbers as $serial) {
            if (is_string($serial) && trim($serial) !== '') {
                $normalized[] = trim($serial);

                continue;
            }

            if (is_array($serial) && filled($serial['serial_no'] ?? null)) {
                $normalized[] = (string) $serial['serial_no'];
            }
        }

        return array_values(array_unique($normalized));
    }

    public static function joinContactParts(string ...$parts): string
    {
        return implode(' / ', array_filter($parts, static fn (string $part): bool => trim($part) !== ''));
    }

    public static function joinAddressParts(?string ...$parts): string
    {
        return trim(implode(' ', array_filter($parts, static fn (?string $part): bool => filled($part))));
    }
}
