<?php

namespace MintyPHP\Module\Notifications\Listeners;

use MintyPHP\App\Module\Contracts\EventListener;
use MintyPHP\Module\Notifications\Service\NotificationMessage;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;

final class UserCreatedNotificationListener implements EventListener
{
    use NotificationListenerTrait;

    public function __construct(
        private readonly NotificationService $notificationService,
        private readonly UserReadRepositoryInterface $userReadRepository,
        private readonly UserTenantRepositoryInterface $userTenantRepository
    ) {
    }

    public function handle(string $event, array $payload): void
    {
        $userId = (int) ($payload['user_id'] ?? 0);
        $uuid = (string) ($payload['uuid'] ?? '');
        $actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;

        if ($userId <= 0 || $uuid === '') {
            return;
        }

        $user = $this->userReadRepository->find($userId);
        if ($user === null) {
            return;
        }

        $displayName = $this->resolveDisplayName($payload, $user, $userId);

        $tenantIds = $this->userTenantRepository->listTenantIdsByUserId($userId);
        if ($tenantIds === []) {
            return;
        }

        $adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
            [PermissionService::USERS_CREATE]
        );
        if ($adminUserIds === []) {
            return;
        }
        $adminSet = array_flip($adminUserIds);

        $link = 'admin/users/edit/' . $uuid;
        $message = NotificationMessage::localized(
            'user.created',
            'New user: %s',
            [$displayName],
            null,
            [],
            $link,
            ['user_id' => $userId, 'uuid' => $uuid]
        );

        foreach ($tenantIds as $tenantId) {
            $this->notificationService->createForTenantAdminUsersFromMessage(
                $tenantId,
                $message,
                $actorUserId,
                $adminSet
            );
        }
    }
}
