<?php


namespace Diamond\Application\GuestBook;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Diamond\Domain\GuestBookItem\Contracts\GuestBookItemEntityInterface;

use Diamond\Application\GuestBook\Dto\CommentRequest;
use Diamond\Repositories\GuestBook\GuestBookRepository;
use Diamond\Repositories\GuestBookItem\GuestBookItemRepository;
use Diamond\Application\GuestBook\Exceptions\GuestBookNotFoundException;

/**
 * Class GuestBookService
 * @package Diamond\Application\GuestBook
 */
class GuestBookService implements RequestAwareInterface
{
    use RequestAwareTrait;


    public function __construct(private GuestBookRepository $bookRepository,
                                private GuestBookItemRepository $guestBookItemRepository)
    {
    }

    /**
     * @return GuestBookRepository
     */
    public function getBookRepository(): GuestBookRepository
    {
        return $this->bookRepository;
    }

    /**
     * @return GuestBookItemRepository
     */
    public function getGuestBookItemRepository(): GuestBookItemRepository
    {
        return $this->guestBookItemRepository;
    }


    /**
     * @param CommentRequest $comment
     * @return GuestBookItemEntityInterface
     */
    public function createComment(CommentRequest $comment): GuestBookItemEntityInterface
    {
        if (!$book = $this->bookRepository->findById($comment->getbookId())) {
            throw new GuestBookNotFoundException(sprintf('book %s not found by id', $comment->getbookId()));
        }

        $comment = GuestBookItemRepository::createEntity()
            ->setText($comment->getComment())
            ->setUseremail($comment->getEmail())
            ->setUsername($comment->getName())
            ->setPublished($comment->getPublished() === true ? "Y" : "N")
            ->setBookId($comment->getbookId())
            ->setIp($this->request->getClientIp())
            ->setRank($comment->getRank())
            ->setObjectId($comment->getObjectId());

        $this->guestBookItemRepository->save($comment);

        return $comment;
    }

}