<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\ConcessionsProvider;
use App\Service\ReportMailer;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
 * Envoi du rapport de scan par email (Excel joint) ou d'un rapport d'erreur.
 * Port de app/api/send-report/route.ts.
 */
#[IsGranted('ROLE_USER')]
final class ReportController extends AbstractController
{
    #[Route('/api/send-report', name: 'app_send_report', methods: ['POST'])]
    public function send(Request $request, ReportMailer $mailer, ConcessionsProvider $provider, LoggerInterface $logger): JsonResponse
    {
        /** @var User $user */
        $user = $this->getUser();
        $email = $user->getUserIdentifier();

        $data = json_decode($request->getContent(), true);
        if (!\is_array($data)) {
            return $this->json(['error' => 'Corps invalide'], Response::HTTP_BAD_REQUEST);
        }

        try {
            if (!empty($data['errorLog']) && \is_string($data['errorLog'])) {
                $mailer->sendError($email, $data['errorLog']);
            } elseif (\is_array($data['results'] ?? null)) {
                $clientConcessions = $data['concessions'] ?? null;
                $concessions = \is_array($clientConcessions)
                    ? array_values(array_filter($clientConcessions, 'is_string'))
                    : $user->getConcessions();
                $mailer->sendReport(
                    $email,
                    $data['results'],
                    (string) ($data['label'] ?? ''),
                    $provider->names($concessions), // IDs → noms affichables

                    \is_string($data['locationNote'] ?? null) ? $data['locationNote'] : null,
                );
            } else {
                return $this->json(['error' => 'Payload invalide'], Response::HTTP_BAD_REQUEST);
            }
        } catch (\Throwable $e) {
            $logger->error('Erreur send-report', ['exception' => $e]);

            return $this->json(['error' => "Erreur lors de l'envoi du rapport."], Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->json(['success' => true]);
    }
}
