<?php

declare(strict_types=1);

namespace App\Module\Mail\Infrastructure\Controller;

use App\Module\Mail\Domain\Exception\MailProviderException;
use App\Module\Mail\Domain\Provider\MailProviderInterface;
use App\Module\Mail\Domain\Repository\MailMessageRepositoryInterface;
use App\Module\Mail\Infrastructure\Security\MailAccessChecker;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/mail/attachments/{downloadId}', name: 'mail_attachment_download', methods: ['GET'], priority: 1)]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class MailAttachmentDownloadController extends AbstractController
{
    public function __construct(
        private readonly MailMessageRepositoryInterface $messageRepository,
        private readonly MailProviderInterface $mailProvider,
        private readonly MailAccessChecker $accessChecker,
    ) {}

    public function __invoke(string $downloadId): Response
    {
        $this->accessChecker->ensureCanAccessMail($this->getUser());

        $decoded = base64_decode(strtr($downloadId, '-_', '+/'), true);
        if (false === $decoded || !str_contains($decoded, ':')) {
            throw new BadRequestHttpException('Invalid attachment ID format');
        }

        [$messageDbIdStr, $partNumber] = explode(':', $decoded, 2);
        $messageDbId                   = (int) $messageDbIdStr;

        $message = $this->messageRepository->findById($messageDbId);
        if (null === $message) {
            throw new NotFoundHttpException('Message not found');
        }

        try {
            $detail = $this->mailProvider->fetchMessage(
                $message->getFolder()->getPath(),
                $message->getUid()
            );
        } catch (MailProviderException) {
            throw new NotFoundHttpException('Could not fetch message from IMAP server');
        }

        $targetAttachment = null;
        foreach ($detail->attachments as $att) {
            if ($att->partNumber === $partNumber) {
                $targetAttachment = $att;

                break;
            }
        }

        if (null === $targetAttachment) {
            throw new NotFoundHttpException(sprintf('Attachment part "%s" not found', $partNumber));
        }

        try {
            $content = $this->mailProvider->fetchAttachment(
                $message->getFolder()->getPath(),
                $message->getUid(),
                $partNumber
            );
        } catch (MailProviderException) {
            throw new NotFoundHttpException('Could not fetch attachment content');
        }

        $filename = basename($targetAttachment->filename);
        if ('' === $filename || '.' === $filename) {
            $filename = 'attachment';
        }

        $response = new Response($content);
        $response->headers->set('Content-Type', $targetAttachment->mimeType);
        $response->headers->set(
            'Content-Disposition',
            sprintf('attachment; filename="%s"', addslashes($filename))
        );
        $response->headers->set('Content-Length', (string) strlen($content));
        $response->headers->set('X-Content-Type-Options', 'nosniff');

        return $response;
    }
}
