<?php

declare(strict_types=1);

namespace SbpJm\FlarumMSTeamsWebhook\Console;

use Flarum\Console\AbstractCommand;
use Flarum\User\User;
use SbpJm\FlarumMSTeamsWebhook\Notification\TestActivityBlueprint;
use SbpJm\FlarumMSTeamsWebhook\Service\TeamsActivityNotifier;
use SbpJm\FlarumMSTeamsWebhook\Support\TargetResolver;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class TestTeamsUserCommand extends AbstractCommand
{
    public function __construct(
        protected TeamsActivityNotifier $notifier,
        protected TargetResolver $targetResolver
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->setName('teams:test-user')
            ->setDescription('Sends a test Microsoft Teams activity feed notification to a Flarum user.')
            ->addArgument('flarumUserId', InputArgument::REQUIRED, 'The numeric Flarum user ID')
            ->addOption('target', null, InputOption::VALUE_OPTIONAL, 'Override the resolved Microsoft Graph target (UPN or Entra user ID)')
            ->addOption('show-target', null, InputOption::VALUE_NONE, 'Only show the resolved Microsoft Graph target, do not send anything');
    }

    protected function fire(): int
    {
        $userId = (int) $this->input->getArgument('flarumUserId');
        $user = User::query()->find($userId);

        if (!$user instanceof User) {
            $this->error('Flarum user not found: ' . $userId);

            return 1;
        }

        $resolvedTarget = $this->targetResolver->resolve($user);
        $overrideTarget = $this->input->getOption('target');
        $target = is_string($overrideTarget) && trim($overrideTarget) !== '' ? trim($overrideTarget) : $resolvedTarget;

        $this->info('Flarum user: #' . $user->id . ' (' . ($user->username ?? $user->display_name ?? 'unknown') . ')');
        $this->info('Email: ' . ($user->email ?? '')); 
        $this->info('Resolved Graph target: ' . ($target ?? '[none]'));

        if ($this->input->getOption('show-target')) {
            return $target ? 0 : 1;
        }

        if ($target === null) {
            $this->error('No Microsoft Graph target could be resolved. Check user_lookup_strategy and related settings.');

            return 1;
        }

        try {
            $blueprint = new TestActivityBlueprint($user);
            $this->notifier->notifyToTarget($user, $blueprint, $target);
            $this->info('Test notification sent successfully.');

            return 0;
        } catch (\Throwable $e) {
            $this->error('Sending failed: ' . $e->getMessage());

            return 1;
        }
    }
}
