package org.lym.pom.controller;

import jakarta.validation.Valid;
import org.lym.pom.dto.posts.PostDTO;
import org.lym.pom.notify.event.PostAddEvent;
import org.lym.pom.notify.publisher.EventPublisher;
import org.lym.pom.repository.mongo.Post;
import org.lym.pom.service.PostService;
import org.shoulder.core.dto.response.BaseResult;
import org.shoulder.core.dto.response.ListResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/api/post")
@Validated
public class PostController extends BaseController {

    @Autowired
    private PostService postService;

    @Autowired
    private EventPublisher eventPublisher;

    /**
     * 添加时刻记录
     *
     * @param post 时刻记录对象（需包含content、type、visibility、creator和device属性）
     * @return 添加后的时刻记录对象
     */
    @PostMapping("add")
    public BaseResult<PostDTO> addPost(@RequestBody @Valid PostDTO post) {
        Post savedPost = postService.addPost(toModel(post));
        eventPublisher.publish(new PostAddEvent(savedPost));
        return BaseResult.success(toDTO(savedPost));
    }

    /**
     * 删除时刻记录
     *
     * @param id 时刻记录 id
     */
    @PostMapping("/delete/{id}")
    public BaseResult<Void> removePost(@PathVariable("id") String id) {
        postService.removePost(id);
        return BaseResult.success();
    }

    /**
     * 根据 id 查询单条时刻记录
     *
     * @param id 时刻记录 id
     * @return 时刻记录详情
     */
    @GetMapping("/{id}")
    public BaseResult<PostDTO> queryPostDetail(@PathVariable("id") String id) {
        Post post = postService.queryPostDetail(id);
        return BaseResult.success(converionService.convert(post, PostDTO.class));
    }

    /**
     * 根据 id 集合查询多条时刻记录
     *
     * @param ids 时刻记录 id 集合
     * @return 时刻记录列表
     */
    @GetMapping("queryList")
    public BaseResult<ListResult<PostDTO>> queryListByIds(@RequestParam Set<String> ids) {
        List<Post> posts = postService.queryListByIds(ids);
        return BaseResult.success(converionService.convert(posts, PostDTO.class));
    }

    private Post toModel(PostDTO dto) {
        return converionService.convert(dto, Post.class);
    }
    private PostDTO toDTO(Post model) {
        return converionService.convert(model, PostDTO.class);
    }

}
