<?php

declare(strict_types=1);

namespace Johncms\Modules\Forum\Application\UseCases;

use Johncms\Modules\Forum\Application\DTO\ReplyMessageContextDTO;
use Johncms\Modules\Forum\Application\Exceptions\ForumAccessDeniedException;
use Johncms\Modules\Forum\Application\Exceptions\ForumNotFoundException;
use Johncms\Modules\Forum\Domain\Repository\ForumMessageRepositoryInterface;
use Johncms\Modules\Forum\Domain\Repository\ForumTopicRepositoryInterface;
use Johncms\Users\User;

final readonly class GetReplyMessageContextUseCase
{
    public function __construct(
        private ForumMessageRepositoryInterface $messageRepository,
        private ForumTopicRepositoryInterface $topicRepository,
        private User $currentUser,
    ) {
    }

    public function execute(int $messageId): ReplyMessageContextDTO
    {
        $config = config('johncms');

        if (
            ! $this->currentUser->isValid()
            || isset($this->currentUser->ban[1])
            || isset($this->currentUser->ban[11])
            || (! $this->currentUser->rights && $config['mod_forum'] === 3)
        ) {
            throw new ForumAccessDeniedException('Access denied to post message.');
        }

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

        if ($this->currentUser->rights < 7 && $message->deleted) {
            throw new ForumNotFoundException('Message not found.');
        }

        $topic = $this->topicRepository->findById((int) $message->topic_id);
        if ($topic === null) {
            throw new ForumNotFoundException('Topic not found.');
        }

        return new ReplyMessageContextDTO($message, $topic);
    }
}
