<?php

namespace MintyPHP\Module\Notifications\Listeners;

trait NotificationListenerTrait
{
    /**
     * Resolve display name from payload with optional fallback to user record.
     *
     * Covers three variants:
     * - payload['display_name'] is present → use it
     * - fallback to user record (display_name, then first+last)
     * - last resort: '#' + user ID
     */
    protected function resolveDisplayName(array $payload, ?array $user, int $userId): string
    {
        $displayName = trim((string) ($payload['display_name'] ?? ''));
        if ($displayName === '' && is_array($user)) {
            $displayName = trim((string) ($user['display_name'] ?? ''));
            if ($displayName === '') {
                $displayName = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
            }
        }
        if ($displayName === '') {
            $displayName = '#' . $userId;
        }

        return $displayName;
    }

    /**
     * Resolve UUID from payload with optional fallback to user record.
     */
    protected function resolveUuid(array $payload, ?array $user): string
    {
        $uuid = trim((string) ($payload['uuid'] ?? ''));
        if ($uuid === '' && is_array($user)) {
            $uuid = trim((string) ($user['uuid'] ?? ''));
        }

        return $uuid;
    }

    /**
     * @return list<int>
     */
    protected function sanitizeTenantIds(mixed $tenantIds): array
    {
        return is_array($tenantIds) ? toIntIds($tenantIds) : [];
    }
}
