<?php

namespace App\Controller;

use App\Entity\Attestation;
use App\Entity\Payout;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class AttestationController extends AbstractController
{
    public function __construct(
        #[Autowire('%kernel.secret%')] private string $appSecret,
    ) {
    }

    #[Route('/attestation/check/{stripePayoutId}', name: 'app_attestation_check')]
    public function check(string $stripePayoutId, EntityManagerInterface $em): Response
    {
        $payout = $em->getRepository(Payout::class)->findOneBy(['stripePayoutId' => $stripePayoutId]);

        $breadcrumbs = [
            ['name' => 'Accueil', 'url' => '/'],
            ['name' => 'Verification attestation', 'url' => '/attestation/check/'.$stripePayoutId],
        ];

        if (!$payout) {
            return $this->render('attestation/not_found.html.twig', [
                'breadcrumbs' => $breadcrumbs,
            ]);
        }

        return $this->render('attestation/check.html.twig', [
            'payout' => $payout,
            'breadcrumbs' => $breadcrumbs,
        ]);
    }

    #[Route('/attestation/ventes/r/{reference}', name: 'app_attestation_ventes_ref')]
    public function ventesRef(string $reference, EntityManagerInterface $em): Response
    {
        $breadcrumbs = [
            ['name' => 'Accueil', 'url' => '/'],
            ['name' => 'Verification attestation de ventes', 'url' => null],
        ];

        $attestation = $em->getRepository(Attestation::class)->findOneBy(['reference' => $reference]);

        if (!$attestation) {
            return $this->render('attestation/not_found_ventes.html.twig', ['breadcrumbs' => $breadcrumbs]);
        }

        return $this->render('attestation/check_ventes.html.twig', [
            'data' => $attestation->getPayload(),
            'breadcrumbs' => $breadcrumbs,
            'isRegistered' => true,
            'attestation' => $attestation,
        ]);
    }

    #[Route('/attestation/ventes/{hash}', name: 'app_attestation_ventes')]
    public function ventes(string $hash, EntityManagerInterface $em): Response
    {
        $breadcrumbs = [
            ['name' => 'Accueil', 'url' => '/'],
            ['name' => 'Verification attestation de ventes', 'url' => null],
        ];

        $decoded = base64_decode(strtr($hash, '-_', '+/'), true);
        if (!$decoded) {
            return $this->render('attestation/not_found_ventes.html.twig', ['breadcrumbs' => $breadcrumbs]);
        }

        $parts = explode('|', $decoded, 2);
        if (2 !== \count($parts)) {
            return $this->render('attestation/not_found_ventes.html.twig', ['breadcrumbs' => $breadcrumbs]);
        }

        [$signature, $jsonPayload] = $parts;
        $expectedSignature = hash_hmac('sha256', $jsonPayload, $this->appSecret);

        if (!hash_equals($expectedSignature, $signature)) {
            return $this->render('attestation/not_found_ventes.html.twig', ['breadcrumbs' => $breadcrumbs]);
        }

        $data = json_decode($jsonPayload, true);
        if (!$data) {
            return $this->render('attestation/not_found_ventes.html.twig', ['breadcrumbs' => $breadcrumbs]);
        }

        $signatureHash = hash_hmac('sha256', $jsonPayload, $this->appSecret);
        $attestation = $em->getRepository(Attestation::class)->findOneBy(['signatureHash' => $signatureHash]);
        $isRegistered = null !== $attestation;

        return $this->render('attestation/check_ventes.html.twig', [
            'data' => $data,
            'breadcrumbs' => $breadcrumbs,
            'isRegistered' => $isRegistered,
            'attestation' => $attestation,
        ]);
    }

    /**
     * @param array<string, mixed> $data
     */
    public static function generateHash(array $data, string $appSecret): string
    {
        $json = json_encode($data, \JSON_UNESCAPED_UNICODE);
        $signature = hash_hmac('sha256', $json, $appSecret);

        return rtrim(strtr(base64_encode($signature.'|'.$json), '+/', '-_'), '=');
    }
}
