package com.nmuzychuk.blog.controller;

import com.nmuzychuk.blog.exceptions.NotFoundException;
import com.nmuzychuk.blog.model.Post;
import com.nmuzychuk.blog.model.User;
import com.nmuzychuk.blog.repository.PostRepository;
import com.nmuzychuk.blog.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.Collection;

/**
 * Controller used to manage posts.
 */
@RestController
public class PostController {

    private final PostRepository postRepository;

    private final UserRepository userRepository;

    @Autowired
    PostController(PostRepository postRepository, UserRepository userRepository) {
        this.postRepository = postRepository;
        this.userRepository = userRepository;
    }

    @RequestMapping(value = "/posts", method = RequestMethod.GET)
    public Collection<Post> readPosts() {
        return postRepository.findAll();
    }

    @RequestMapping(value = "/users/{userId}/posts", method = RequestMethod.GET)
    public Collection<Post> readUserPosts(@PathVariable Long userId) {
        return postRepository.findByUserId(userId);
    }

    @RequestMapping(value = "/users/{userId}/posts", method = RequestMethod.POST)
    public ResponseEntity<?> createUserPost(@PathVariable Long userId, @RequestBody Post post) {
        User user = userRepository.findById(userId);
        post.setUser(user);

        Post savedPost = postRepository.save(post);

        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{id}")
                .buildAndExpand(savedPost.getId()).toUri();

        return ResponseEntity.created(location).build();
    }

    @RequestMapping(value = "/posts/{postId}", method = RequestMethod.GET)
    public Post readPost(@PathVariable Long postId) {
        Post post = postRepository.findById(postId);

        if (post != null) {
            return post;
        } else {
            throw new NotFoundException(Post.class.toString(), postId);
        }
    }

}

@@ -467,31 +467,64 @@
 web.
-servlet.support.Servlet
+util.UriComponents;%0Aimport org.springframework.web.util.
 UriC
@@ -546,29 +546,8 @@
 r;%0A%0A
-import java.net.URI;%0A
 impo
@@ -1502,16 +1502,90 @@
 ost post
+,%0A                                            UriComponentsBuilder builder
 ) %7B%0A    
@@ -1661,17 +1661,16 @@
 (user);%0A
-%0A
         
@@ -1727,30 +1727,22 @@
    U
-RI location = ServletU
+riComponents u
 riCo
@@ -1749,23 +1749,18 @@
 mponents
-Builder
+ =
 %0A       
@@ -1772,60 +1772,39 @@
     
-.fromCurrentRequest().path(%22/%7Bid%7D%22)%0A                
+builder.path(%22/posts/%7BpostId%7D%22)
 .bui
@@ -1837,16 +1837,8 @@
 d())
-.toUri()
 ;%0A%0A 
@@ -1878,16 +1878,29 @@
 ted(
-location
+uriComponents.toUri()
 ).bu

Fix post location header