<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\Image;
use App\Entity\SharedImage;
use App\Entity\User;
use App\Enum\TokenType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Mailer\MailerInterface;

class ShareService
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly TokenService           $tokenService,
        private readonly MailerInterface        $mailer,
        #[Autowire('%env(int:SHARE_TOKEN_TTL_DAYS)%')]
        private readonly int                    $tokenTtlDays,
        #[Autowire('%env(MAILER_SENDER)%')]
        private readonly string                 $mailerSender,
    ) {}

    public function share(Image $image, User $sharer, string $recipientEmail): SharedImage
    {
        $recipient = $this->em->getRepository(User::class)->findOneBy(['email' => $recipientEmail]);

        if ($recipient === null) {
            throw new \InvalidArgumentException('Recipient not found. They must have an account to receive shared photos.');
        }

        if ($recipient->getId() === $sharer->getId()) {
            throw new \InvalidArgumentException('You cannot share a photo with yourself.');
        }

        // Idempotent: return existing pending share if one already exists
        $existing = $this->em->getRepository(SharedImage::class)->findOneBy([
            'sourceImage'   => $image,
            'recipientUser' => $recipient,
        ]);
        if ($existing) {
            return $existing;
        }

        $shared = new SharedImage($image, $recipient, $sharer);
        $this->em->persist($shared);

        $approveToken = $this->tokenService->issue(TokenType::ShareApprove, $image, $recipient, $recipientEmail, $this->tokenTtlDays);
        $declineToken = $this->tokenService->issue(TokenType::ShareDecline, $image, $recipient, $recipientEmail, $this->tokenTtlDays);

        $this->em->flush();

        $email = (new TemplatedEmail())
            ->from($this->mailerSender)
            ->to($recipientEmail)
            ->subject($sharer->getEmail() . ' shared a photo with you')
            ->htmlTemplate('emails/share_notification.html.twig')
            ->textTemplate('emails/share_notification.txt.twig')
            ->context([
                'sharer'       => $sharer,
                'image'        => $image,
                'approveToken' => $approveToken,
                'declineToken' => $declineToken,
            ]);

        $this->mailer->send($email);

        return $shared;
    }
}
