<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Controller\Page;

use Contao\CoreBundle\Repository\WebauthnCredentialRepository;
use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\ApiToken;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Generator\ApiTokenGenerator;
use Ferienpass\CoreBundle\Repository\WebauthnUserEntityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Translation\TranslatableMessage;

#[Route('/sicherheit')]
final class SecurityController extends AbstractController
{
    private const string TMP_SESSION_KEY = 'admin_security_api_token:value';

    #[Route('', name: 'admin_security')]
    public function __invoke(EntityManagerInterface $em, Request $request, \Ferienpass\AdminBundle\Breadcrumb\Breadcrumb $breadcrumb): Response
    {
        /** @noinspection FormViewTemplate `createView()` messes ups error handling/redirect */
        return $this->render('@FerienpassAdmin/page/user/security.html.twig', [
            'breadcrumb' => $breadcrumb->generate('userAccount.security.title'),
        ]);
    }

    #[Route('/api-token', name: 'admin_security_api_token')]
    public function apiToken(#[CurrentUser] User $user, Request $request, EntityManagerInterface $entityManager, ApiTokenGenerator $apiTokenGenerator, UserPasswordHasherInterface $passwordHasher): Response
    {
        $session = $request->getSession();
        $fb = $this->createFormBuilder(options: [
            'action' => $this->generateUrl('admin_security_api_token'),
        ]);

        $fb->add('api:offer', ChoiceType::class, [
            'choices' => [
                'api:offer:read',
                // 'api:offer:write',
            ],
            'choice_label' => static fn ($choice): TranslatableMessage => new TranslatableMessage($choice, domain: 'admin'),
            'expanded' => true,
            'required' => false,
            'multiple' => false,
            'label' => 'Angebote',
        ]);

        $form = $fb->getForm();

        if ($session->has(self::TMP_SESSION_KEY)) {
            $apiToken = $session->get(self::TMP_SESSION_KEY);
            $session->remove(self::TMP_SESSION_KEY);

            $token = $entityManager->getRepository(ApiToken::class)->findOneBy(['locator' => explode('.', (string) $apiToken)[0]]);

            return $this->render('@FerienpassAdmin/page/security/api-token.html.twig', [
                'token' => $token,
                'apiToken' => $apiToken,
            ]);
        }

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $apiToken = $apiTokenGenerator->generate();
            $session->set(self::TMP_SESSION_KEY, $apiToken);

            $scopes = array_values(array_filter($form->getData(), static fn ($v) => str_starts_with((string) $v, 'api:')));
            $token = ApiToken::fromToken($apiToken, $scopes, $user, $passwordHasher);

            $entityManager->persist($token);
            $entityManager->flush();

            return $this->redirectToRoute('admin_security_api_token');
        }

        return $this->render('@FerienpassAdmin/page/security/api-token.html.twig', [
            'form' => $form,
        ]);
    }

    /**
     * Revoke (delete) an API token belonging to the current user. We resolve
     * the token via the URL `{id}` and double-check ownership before deleting
     * so a logged-in user can't revoke someone else's token even with a valid
     * CSRF.
     */
    #[Route('/sicherheit/api-token/{id}/revoke', name: 'admin_security_api_token_revoke', methods: ['POST'])]
    public function revokeApiToken(
        int $id,
        #[CurrentUser]
        User $user,
        Request $request,
        EntityManagerInterface $em,
    ): Response {
        if (!$this->isCsrfTokenValid('submit', (string) $request->request->get('_token'))) {
            throw $this->createAccessDeniedException();
        }

        $token = $em->getRepository(ApiToken::class)->find($id);
        if (null === $token || $token->getOwnedBy() !== $user) {
            throw $this->createNotFoundException();
        }

        $em->remove($token);
        $em->flush();

        $this->addFlash('success', 'API-Token widerrufen.');

        return $this->redirectToRoute('admin_security');
    }

    /**
     * Detach the user's password. Allowed only when at least one passkey
     * exists — otherwise removing the password would leave magic-link as the
     * only sign-in method, and a single mailbox compromise = full account
     * takeover. We treat passkeys as the only acceptable "second factor"
     * substitute.
     */
    #[Route('/sicherheit/password/remove', name: 'admin_security_remove_password', methods: ['POST'])]
    public function removePassword(
        #[CurrentUser]
        User $user,
        Request $request,
        EntityManagerInterface $em,
        WebauthnUserEntityRepository $userEntities,
        #[Autowire(service: 'contao.repository.webauthn_credential')]
        WebauthnCredentialRepository $credentials,
    ): Response {
        if (!$this->isCsrfTokenValid('submit', (string) $request->request->get('_token'))) {
            throw $this->createAccessDeniedException();
        }

        $userEntity = $userEntities->findOneByUsername($user->getUsername());
        $passkeys = null !== $userEntity ? $credentials->findAllForUserEntity($userEntity) : [];

        if (\count($passkeys) < 1) {
            $this->addFlash('error', 'Bitte hinterlegen Sie zuerst einen Passkey, bevor Sie Ihr Passwort entfernen.');

            return $this->redirectToRoute('admin_security');
        }

        $user->clearPassword();
        $em->flush();

        $this->addFlash('success', 'Passwort entfernt. Sie können sich jetzt ausschließlich per Passkey oder Anmeldelink anmelden.');

        return $this->redirectToRoute('admin_security');
    }

    /**
     * Flip per-user magic-link sign-in. Refused when it would leave the user
     * with no fall-back method (no password and no passkey on file).
     */
    #[Route('/sicherheit/magic-links/toggle', name: 'admin_security_toggle_magic_links', methods: ['POST'])]
    public function toggleMagicLinks(
        #[CurrentUser]
        User $user,
        Request $request,
        EntityManagerInterface $em,
        WebauthnUserEntityRepository $userEntities,
        #[Autowire(service: 'contao.repository.webauthn_credential')]
        WebauthnCredentialRepository $credentials,
    ): Response {
        if (!$this->isCsrfTokenValid('submit', (string) $request->request->get('_token'))) {
            throw $this->createAccessDeniedException();
        }

        $turningOff = !$user->isMagicLinksDisabled();

        if ($turningOff) {
            // Need at least one alternative method present.
            $hasPassword = null !== $user->getPassword();
            $userEntity = $userEntities->findOneByUsername($user->getUsername());
            $passkeyCount = null !== $userEntity ? \count($credentials->findAllForUserEntity($userEntity)) : 0;

            if (!$hasPassword && $passkeyCount < 1) {
                $this->addFlash('error', 'Sie können den Anmeldelink nicht deaktivieren, solange Sie weder Passwort noch Passkey gesetzt haben.');

                return $this->redirectToRoute('admin_security');
            }
        }

        $user->setMagicLinksDisabled($turningOff);
        $em->flush();

        $this->addFlash(
            'success',
            $turningOff
                ? 'Anmeldelink für Ihr Konto deaktiviert.'
                : 'Anmeldelink für Ihr Konto wieder aktiviert.'
        );

        return $this->redirectToRoute('admin_security');
    }
}
