package ovh.herisson.Clyde.EndPoints;


import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.UserService;
import ovh.herisson.Clyde.Tables.User;


@RestController
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class UserController {

    private final UserService userService;
    private final AuthenticatorService authServ;
    public UserController(UserService userService, AuthenticatorService authServ){
        this.userService = userService;
        this.authServ = authServ;
    }

    @GetMapping("/user")
    public ResponseEntity<User> getUser(@RequestHeader("Cookie") String authorization){

        if (authorization == null) return new UnauthorizedResponse<>(null);
        User user = authServ.getUserFromToken(authorization);
        if (user == null) return new UnauthorizedResponse<>(null);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @PostMapping("/user") //todo check role
    public ResponseEntity<String> postUser(@RequestBody User user){
        userService.save(user);
        return new ResponseEntity<>(String.format("Account created with ID:%s",user.getRegNo()),HttpStatus.CREATED);
    }

    @GetMapping("/users")
    public Iterable<User> getAllUsers(){
        return userService.getAll();
    }


}

