"""Publish post use case.""" from uuid import UUID from app.application.dtos.post import PostResponseDTO from app.application.interfaces import TransactionManager from app.domain.entities import Post from app.domain.exceptions import ForbiddenException, NotFoundException from app.domain.repositories import PostRepository class PublishPostUseCase: """Use case for publishing/unpublishing a blog post.""" def __init__( self, post_repo: PostRepository, tx_manager: TransactionManager, ) -> None: self._post_repo = post_repo self._tx_manager = tx_manager async def publish(self, post_id: UUID, current_user_id: str) -> PostResponseDTO: """Publish a post.""" post = await self._post_repo.get_by_id(post_id) if not post: raise NotFoundException(f"Post with id '{post_id}' not found") if post.author_id != current_user_id: raise ForbiddenException("You can only publish your own posts") post.publish() await self._post_repo.update(post) await self._tx_manager.commit() return self._map_to_dto(post) async def unpublish(self, post_id: UUID, current_user_id: str) -> PostResponseDTO: """Unpublish a post.""" post = await self._post_repo.get_by_id(post_id) if not post: raise NotFoundException(f"Post with id '{post_id}' not found") if post.author_id != current_user_id: raise ForbiddenException("You can only unpublish your own posts") post.unpublish() await self._post_repo.update(post) await self._tx_manager.commit() return self._map_to_dto(post) def _map_to_dto(self, post: Post) -> PostResponseDTO: """Map domain entity to response DTO.""" return PostResponseDTO( id=post.id, title=post.title.value, content=post.content.value, slug=post.slug.value, author_id=post.author_id, published=post.published, tags=post.tags.copy(), created_at=post.created_at, updated_at=post.updated_at, )