<?php

namespace App\Controller\Api;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/account')]
class ApiAccountController extends AbstractController
{
    use ApiAuthTrait;

    /** @codeCoverageIgnore Autowire injection */
    public function __construct(
        #[Autowire('%kernel.secret%')] private string $appSecret,
    ) {
    }

    #[Route('/lookup', name: 'app_api_account_lookup', methods: ['POST'])]
    public function lookup(
        Request $request,
        EntityManagerInterface $em,
    ): JsonResponse {
        $secret = $request->headers->get('X-App-Secret', '');

        if ('' === $secret || !hash_equals($this->appSecret, $secret)) {
            return $this->error('Secret invalide.', 401);
        }

        $data = json_decode($request->getContent(), true);
        $email = $data['email'] ?? '';

        if ('' === $email) {
            return $this->error('Email requis.');
        }

        $user = $em->getRepository(User::class)->findOneBy(['email' => $email]);

        return $user
            ? $this->success(['id' => $user->getId(), 'stripeAccountId' => $user->getStripeAccountId()])
            : $this->error('Utilisateur introuvable.', 404);
    }
}
