<?php

declare(strict_types=1);

namespace App\Mcp\Security;

use App\Repository\ProfileRepository;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

#[AsEventListener(event: ConsoleEvents::COMMAND)]
final class McpStdioAuthSubscriber
{
    public function __construct(
        private readonly ProfileRepository $profiles,
        private readonly UserPasswordHasherInterface $passwordHasher,
        private readonly TokenStorageInterface $tokenStorage,
        private readonly LoggerInterface $logger,
    ) {}

    public function __invoke(ConsoleCommandEvent $event): void
    {
        $command = $event->getCommand();

        if (!$command || !str_starts_with($command->getName() ?? '', 'mcp:')) {
            return;
        }

        $profileId = $_ENV['MCP_PROFILE_ID'] ?? '';
        $password  = $_ENV['MCP_PROFILE_PASSWORD'] ?? '';

        if ('' === $profileId || '' === $password) {
            $this->logger->error('MCP stdio: missing MCP_PROFILE_ID or MCP_PROFILE_PASSWORD env vars');
            $event->disableCommand();
            $event->getOutput()->writeln('<error>MCP auth: MCP_PROFILE_ID and MCP_PROFILE_PASSWORD env vars required</error>');

            return;
        }

        $profile = $this->profiles->find($profileId);

        if (!$profile || !$profile->isActive()) {
            $this->logger->error('MCP stdio: profile not found or inactive', ['profileId' => $profileId]);
            $event->disableCommand();
            $event->getOutput()->writeln('<error>MCP auth: invalid profile</error>');

            return;
        }

        if (!$this->passwordHasher->isPasswordValid($profile, $password)) {
            $this->logger->error('MCP stdio: invalid password', ['profileId' => $profileId]);
            $event->disableCommand();
            $event->getOutput()->writeln('<error>MCP auth: invalid password</error>');

            return;
        }

        $token = new UsernamePasswordToken($profile, 'mcp', $profile->getRoles());
        $this->tokenStorage->setToken($token);

        $this->logger->info('MCP stdio auth success', [
            'profileId' => $profileId,
            'roles'     => $profile->getRoles(),
        ]);
    }
}
