<?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\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;

final class UserDeletedNotificationListener implements EventListener
{
    use NotificationListenerTrait;

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

    public function handle(string $event, array $payload): void
    {
        $userId = (int) ($payload['user_id'] ?? 0);
        if ($userId <= 0) {
            return;
        }

        // Belt-and-suspenders cleanup (DB CASCADE handles this too)
        $this->notificationService->deleteAllForUser($userId);

        // Notify admins about the deletion
        $displayName = trim((string) ($payload['display_name'] ?? ''));
        $tenantIds = (array) ($payload['tenant_ids'] ?? []);
        $actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;

        if ($displayName === '' || $tenantIds === []) {
            return;
        }

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

        $message = NotificationMessage::localized(
            'user.deleted',
            'User deleted: %s',
            [$displayName],
            null,
            [],
            null,
            ['user_id' => $userId]
        );

        foreach ($tenantIds as $tenantId) {
            $tenantId = (int) $tenantId;
            if ($tenantId <= 0) {
                continue;
            }

            $this->notificationService->createForTenantAdminUsersFromMessage(
                $tenantId,
                $message,
                $actorUserId,
                $adminSet
            );
        }
    }
}
