package de.oaa.xxx.user;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
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.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping
    public ResponseEntity<Void> userAnlegen(@RequestBody Registration registration) {
        if (registration.getEmail() == null || registration.getPasswordHash() == null || registration.getName() == null) {
            return ResponseEntity.badRequest().build();
        }
        if (userRepository.findByEmail(registration.getEmail()).isPresent()) {
            LOGGER.warn("User mit E-Mail {} bereits vorhanden", registration.getEmail());
            return ResponseEntity.status(409).build();
        }
        try {
            UserEntity entity = new UserEntity();
            entity.setUserId(UUID.randomUUID());
            entity.setEmail(registration.getEmail());
            entity.setName(registration.getName());
            entity.setPassword(registration.getPasswordHash());
            userRepository.save(entity);
            return ResponseEntity.status(201).build();
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            return ResponseEntity.internalServerError().build();
        }
    }
}
