<?php

declare(strict_types=1);

namespace SbpJm\FlarumMSTeamsWebhook\Listener;

use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\User;
use Illuminate\Contracts\Queue\Queue;
use SbpJm\FlarumMSTeamsWebhook\Job\SendTeamsActivityNotificationJob;
use SbpJm\FlarumMSTeamsWebhook\Support\TargetResolver;

class MirrorAlertsToTeams
{
    public function __construct(
        protected SettingsRepositoryInterface $settings,
        protected Queue $queue,
        protected TargetResolver $targetResolver
    ) {
    }

    /**
     * @param User[] $newRecipients
     * @return User[]
     */
    public function __invoke(BlueprintInterface $blueprint, array $newRecipients): array
    {
        if (!$this->isEnabled()) {
            return $newRecipients;
        }

        foreach ($newRecipients as $user) {
            if (!$user instanceof User) {
                continue;
            }

            if (!$this->shouldMirrorForUser($user, $blueprint)) {
                continue;
            }

            if ($this->targetResolver->resolve($user) === null) {
                continue;
            }

            $this->queue->push(new SendTeamsActivityNotificationJob($blueprint, $user));
        }

        return $newRecipients;
    }

    protected function isEnabled(): bool
    {
        return filter_var($this->settings->get('sbp-jm-msteams-webhook.enabled', '0'), FILTER_VALIDATE_BOOLEAN);
    }

    protected function shouldMirrorForUser(User $user, BlueprintInterface $blueprint): bool
    {
        $webPreferenceKey = User::getNotificationPreferenceKey($blueprint::getType(), 'alert');
        $webEnabled = (bool) $user->getPreference($webPreferenceKey, false);

        if (!$webEnabled) {
            return false;
        }

        $globalOptOutKey = 'sbp-jm-msteams-webhook.user_disabled';

        return !(bool) $user->getPreference($globalOptOutKey, false);
    }
}
