package com.social.media.application.content.handler;

import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.social.media.application.content.dto.PostResponseDto;
import com.social.media.application.content.query.GetPostByIdQuery;
import com.social.media.domain.content.aggregate.Post;
import com.social.media.domain.content.repository.PostRepository;

@Service
@Transactional(readOnly = true)
public class GetPostByIdQueryHandler {
    
    private final PostRepository postRepository;
    
    public GetPostByIdQueryHandler(PostRepository postRepository) {
        this.postRepository = postRepository;
    }
    
    public PostResponseDto handle(GetPostByIdQuery query) {
        Post post = postRepository.findById(query.postId())
            .orElseThrow(() -> new RuntimeException(
                "Post not found: " + query.postId()
            ));
        
        return mapToDto(post);
    }
    
    private PostResponseDto mapToDto(Post post) {
        return PostResponseDto.builder()
            .id(post.getId().value().toString())
            .companyId(post.getCompanyId().value().toString())
            .authorId(post.getAuthorId().value().toString())
            .categoryId(post.getCategoryId() != null ? post.getCategoryId().value().toString() : null)
            .title("")
            .content(post.getContent().text())
            .postType(post.getPostType().name())
            .status(post.getStatus().name())
            .mediaIds(post.getMediaIds().stream().map(id -> id.value().toString()).toList())
            .targetSocialAccountIds(post.getTargetSocialAccounts().stream()
                .map(id -> id.value().toString())
                .collect(Collectors.toSet()))
            .scheduledFor(post.getScheduledFor())
            .publishedAt(post.getPublishedAt())
            .createdAt(post.getCreatedAt())
            .updatedAt(post.getUpdatedAt())
            .tags(post.getTags())
            .isPinned(post.isPinned())
            .viewCount(post.getViewCount())
            .likeCount(post.getLikeCount())
            .shareCount(post.getShareCount())
            .commentCount(post.getCommentCount())
            .hashtags(post.getHashtags())
            .mentions(post.getMentions())
            .build();
    }
}

