<?php

declare(strict_types=1);

namespace App\Business\DataImport\Support;

use App\Business\DataImport\DataImportRow;

final class DataImportRowSnapshotEncoder
{
    /**
     * @var list<string>
     */
    private const SENSITIVE_FIELDS = [
        'mobile',
        'phone',
        'email',
    ];

    /**
     * @return array<string, string|null>
     */
    public static function fromRow(DataImportRow $row): array
    {
        return $row->values;
    }

    /**
     * @param  array<string, string|null>  $snapshot
     * @return array<string, string|null>
     */
    public static function forDisplay(array $snapshot): array
    {
        $values = $snapshot;

        foreach ($values as $field => $value) {
            if (! is_string($field) || $value === null || $value === '') {
                continue;
            }

            if (in_array($field, self::SENSITIVE_FIELDS, true)) {
                $values[$field] = self::maskSensitiveValue($field, $value);
            }
        }

        return $values;
    }

    private static function maskSensitiveValue(string $field, string $value): string
    {
        if ($field === 'email' && str_contains($value, '@')) {
            [$local, $domain] = explode('@', $value, 2);

            if ($local === '') {
                return '***@'.$domain;
            }

            return mb_substr($local, 0, 1).'***@'.$domain;
        }

        $length = mb_strlen($value);

        if ($length <= 4) {
            return str_repeat('*', $length);
        }

        return mb_substr($value, 0, 3).str_repeat('*', max(1, $length - 7)).mb_substr($value, -4);
    }
}
