package com.kalyshev.yan.user.controller;

import com.kalyshev.yan.WebConfiguration;
import com.kalyshev.yan.user.model.User;
import com.kalyshev.yan.user.service.UserService;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(WebConfiguration.REST_API + "/user")
public class UserController {
    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }
    @GetMapping("/{id}")
    public UserDto getUser(@PathVariable Long id) {
        return new UserDto(userService.findUser(id));
    }
    @GetMapping("/")
    public List<UserDto> getAllUsers(
            @RequestParam(value = "pageNo", defaultValue = "0", required = false) int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            @RequestParam(value = "sortBy", defaultValue = "id", required = false) String sortBy,
            @RequestParam(value = "sortDir", defaultValue = "asc", required = false) String sortDir
    ){
        return userService.findAllUsers(pageNo, pageSize, sortBy, sortDir);
    }
    @GetMapping("/tryLogin")
    public User tryLogin(
            @RequestParam(value = "login") String login,
            @RequestParam(value = "password") String password
    ){
        return userService.tryLogin(login, password);
    }
    @PostMapping("/")
    public UserDto createUser(@RequestBody @Valid UserDto userDto) {
        return new UserDto(userService.addUser(userDto.getLogin(), userDto.getFio(), userDto.getPhone(), userDto.getPassword(), userDto.getRole()));
    }
    @PutMapping("/{id}")
    public UserDto updateUser(@PathVariable Long id,
                                  @RequestBody @Valid UserDto userDto) {
        return new UserDto(userService.updateUser(id, userDto.getLogin(), userDto.getFio(), userDto.getPhone(), userDto.getPassword(), userDto.getRole()));
    }
    @DeleteMapping("/{id}")
    public UserDto deleteUser(@PathVariable Long id) {
        return new UserDto(userService.deleteUser(id));
    }
    @DeleteMapping("/")
    public void deleteAllUsers() {
        userService.deleteAllUsers();
    }
}