<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\Device;
use App\Entity\User;
use App\Enum\Orientation;
use App\Form\RegistrationFormType;
use App\Service\DeviceClaimRequiredException;
use App\Service\DeviceService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
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\IsGranted;

#[Route('/setup/{mac}', requirements: ['mac' => '[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}'])]
class SetupController extends AbstractController
{
    #[Route('', name: 'setup_index', methods: ['GET', 'POST'])]
    public function index(
        string $mac,
        Request $request,
        UserPasswordHasherInterface $hasher,
        EntityManagerInterface $em,
        Security $security,
        DeviceService $deviceService,
    ): Response {
        // If already authenticated, try to link silently. If the MAC is owned
        // by someone else, fall through to the form so the user has to tick
        // the "Claim this frame" checkbox before transferring ownership.
        if ($this->getUser()) {
            /** @var User $user */
            $user = $this->getUser();
            if (!$deviceService->isClaimedByAnotherUser($mac, $user)) {
                $device = $deviceService->linkToUser($mac, $user);
                return $this->postLinkRedirect($device);
            }
        }

        $regForm  = $this->createForm(RegistrationFormType::class, new User(), [
            'action' => $this->generateUrl('setup_register', ['mac' => $mac]),
        ]);
        $loginError = $request->getSession()->get('_setup_login_error');
        $request->getSession()->remove('_setup_login_error');
        $claimError = $request->getSession()->get('_setup_claim_error');
        $request->getSession()->remove('_setup_claim_error');

        // The setup page only knows about the MAC at this point — the
        // candidate user is whoever's logging in / registering — so we can't
        // call isClaimedByAnotherUser() yet. We just check "is the MAC bound
        // to anyone at all?" which is enough to surface the checkbox.
        $existing = $em->getRepository(Device::class)->findOneBy(['mac' => strtoupper($mac)]);
        $alreadyClaimed = $existing !== null && $existing->getUser() !== null;

        return $this->render('setup/index.html.twig', [
            'mac'             => $mac,
            'reg_form'        => $regForm,
            'login_error'     => $loginError,
            'already_claimed' => $alreadyClaimed,
            'claim_error'     => $claimError,
        ]);
    }

    #[Route('/register', name: 'setup_register', methods: ['POST'])]
    public function register(
        string $mac,
        Request $request,
        UserPasswordHasherInterface $hasher,
        EntityManagerInterface $em,
        Security $security,
        DeviceService $deviceService,
    ): Response {
        $user = new User();
        $form = $this->createForm(RegistrationFormType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var string $plain */
            $plain = $form->get('plainPassword')->getData();
            $user->setPassword($hasher->hashPassword($user, $plain));
            $em->persist($user);
            $em->flush();

            $security->login($user, 'form_login', 'main');

            $allowClaim = $request->request->getBoolean('claim_device');
            try {
                $device = $deviceService->linkToUser($mac, $user, $allowClaim);
            } catch (DeviceClaimRequiredException) {
                // New account just created and claim wasn't acknowledged.
                // Bounce back through the setup page; the checkbox will be
                // visible because the device is now bound (to no one — wait,
                // actually still bound to the prior owner since we threw
                // before persisting).
                $request->getSession()->set(
                    '_setup_claim_error',
                    'This frame is already linked to another account. Tick "Claim this frame" to take it over and erase the previous owner\'s photos.',
                );
                return $this->redirectToRoute('setup_index', ['mac' => $mac]);
            }

            return $this->postLinkRedirect($device);
        }

        $existing = $em->getRepository(Device::class)->findOneBy(['mac' => strtoupper($mac)]);
        return $this->render('setup/index.html.twig', [
            'mac'             => $mac,
            'reg_form'        => $form,
            'login_error'     => null,
            'already_claimed' => $existing !== null && $existing->getUser() !== null,
            'claim_error'     => null,
        ]);
    }

    #[Route('/login', name: 'setup_login', methods: ['POST'])]
    public function login(
        string $mac,
        Request $request,
        UserPasswordHasherInterface $hasher,
        EntityManagerInterface $em,
        Security $security,
        DeviceService $deviceService,
    ): Response {
        $email    = trim((string) $request->request->get('_username', ''));
        $password = (string) $request->request->get('_password', '');

        $user = $em->getRepository(User::class)->findOneBy(['email' => $email]);
        if ($user && $hasher->isPasswordValid($user, $password)) {
            $security->login($user, 'form_login', 'main');
            $allowClaim = $request->request->getBoolean('claim_device');
            try {
                $device = $deviceService->linkToUser($mac, $user, $allowClaim);
            } catch (DeviceClaimRequiredException) {
                $request->getSession()->set(
                    '_setup_claim_error',
                    'This frame is already linked to another account. Tick "Claim this frame" to take it over and erase the previous owner\'s photos.',
                );
                return $this->redirectToRoute('setup_index', ['mac' => $mac]);
            }
            return $this->postLinkRedirect($device);
        }

        $request->getSession()->set('_setup_login_error', 'Incorrect email or password');
        return $this->redirectToRoute('setup_index', ['mac' => $mac]);
    }

    /**
     * Legacy route — first-time configuration now happens in the SPA's
     * settings sheet (auto-opens via the ?setup=<id> query param) so users
     * see the same controls as live editing, with their theme applied,
     * pre-populated from the device's current state. Kept as a redirect so
     * any in-flight bookmarks land in the right place.
     */
    #[Route('/configure', name: 'setup_configure', methods: ['GET', 'POST'])]
    #[IsGranted('ROLE_USER')]
    public function configure(
        string $mac,
        DeviceService $deviceService,
    ): Response {
        /** @var User $user */
        $user   = $this->getUser();
        $device = $deviceService->linkToUser($mac, $user);
        return $this->postLinkRedirect($device);
    }

    /**
     * After linkToUser, hand off to the SPA. If the device hasn't been
     * named yet (= first-time setup), append ?setup=<id> so the SPA
     * auto-opens its settings sheet for that device. Avoids duplicating
     * the rich settings UI in a plain-Twig setup page.
     */
    private function postLinkRedirect(Device $device): Response
    {
        if (empty($device->getName())) {
            return $this->redirect('/?setup=' . $device->getId());
        }
        return $this->redirectToRoute('spa');
    }
}
