package com.jpa.jpaspringboot.controller;

import com.jpa.jpaspringboot.entity.User;
import com.jpa.jpaspringboot.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * GET查询，POST新增，PUT更新，DELETE删除
 */

@RestController
@CrossOrigin
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 查询所有用户
     * @return 查询出的用户
     */
    @GetMapping
    public List<User> find() {
        return userService.find();
    }
// addUsers = add(动词crud) -> http method 代替动词 + User(名词)
    /**
     * 插入一个用户对象
     *
     * @param user 待插入的对象，ID为0或者null
     * @return 插入后的对象，一般来说id会更新
     */
    @PostMapping
    public ResponseEntity<User> insert(@RequestBody User user) {
        User result = userService.insert(user);
        if (result.getId() == null || result.getId() == 0) {
            return ResponseEntity.status(400).body(result);
        } else {
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 按id删除数据
     * @param id 需要删除的用户信息
     * @return
     */
    @DeleteMapping("{id}")
    public ResponseEntity<Integer> delete(@PathVariable Integer id){
        userService.delete(id);
        if (id == 0 || id == null){
            return ResponseEntity.status(404).body(id);
        }else {
            return ResponseEntity.ok(id);
        }
    }

    /**
     * 按ID修改用户信息
     * @param user 用户的信息，根据用户信息中的id查找需要修改的用户信息
     * @return
     */
    @PutMapping("{id}")
    public ResponseEntity<User> update(@RequestBody User user){
        User result =  userService.update(user);
        if (result.getId() == 0 || result.getId() == null){
            return ResponseEntity.status(400).body(result);
        }else {
            return ResponseEntity.ok(result);
        }
    }
    /**
     * 按ID修改用户信息
     * @param user 用户的信息，根据用户信息中的id查找需要修改的用户信息
     * @return
     */
    @PatchMapping("{id}")
    public ResponseEntity<User> patch(@RequestBody User user){
        User result = userService.patch(user);
        if (result.getId() == null || result.getId() == 0){
            return ResponseEntity.status(400).body(result);
        }else {
            return ResponseEntity.ok(result);
        }
    }


}
