<?php

namespace App\Actions\V1\Blog;

use App\Dto\V1\BlogDto;
use App\Exceptions\LogicalException;
use App\Models\Blog;
use App\Repositories\V1\Blogs\BlogImageRepositoryInterface;
use App\Repositories\V1\Blogs\BlogRepositoryInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;

readonly class UpdateBlogAction
{
    public function __construct(
        private BlogRepositoryInterface $blogRepository,
        private BlogImageRepositoryInterface $blogImageRepository
    ) {}

    /**
     * @throws LogicalException
     */
    public function execute(int $blogId, BlogDto $dto): Blog
    {
        $blog = $this->blogRepository->getById($blogId);

        if (! $blog) {
            throw new ModelNotFoundException(__('exceptions.project_not_found'));
        }

        $currentImagesCount = $this->blogImageRepository
            ->getCountByBlogId($blogId);

        $afterDeleteCount = $currentImagesCount - count($dto->deletedImages);

        if ($afterDeleteCount + count($dto->images) > config('general.project_image_limit')) {
            throw new LogicalException(__('exceptions.images_max_has_been_exceeded'));
        }

        $this->blogRepository->update(
            $blogId,
            $dto->blogUpdatePayload()
        );

        if (! empty($dto->deletedImages)) {
            $this->blogImageRepository->deleteByIds(
                $blogId,
                $dto->deletedImages
            );
        }

        if (! empty($dto->images)) {
            $this->blogImageRepository->create(
                $blogId,
                $dto->images
            );
        }

        return $this->blogRepository->getById($blogId);
    }
}
