<?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 UserActivatedNotificationListener 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);
        if ($userId <= 0) {
            return;
        }

        $user = $this->userReadRepository->find($userId);
        $displayName = $this->resolveDisplayName($payload, $user, $userId);
        $uuid = $this->resolveUuid($payload, $user);

        $tenantIds = $this->sanitizeTenantIds($payload['tenant_ids'] ?? []);
        if ($tenantIds === []) {
            $tenantIds = $this->userTenantRepository->listTenantIdsByUserId($userId);
        }
        if ($tenantIds === []) {
            return;
        }

        $adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
            [PermissionService::USERS_UPDATE]
        );
        if ($adminUserIds === []) {
            return;
        }
        $adminSet = array_fill_keys(array_map('intval', $adminUserIds), true);
        $actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;

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

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