package de.oaa.xxx.user;

import java.util.Optional;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/login")
public class LoginController {

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

    private final UserRepository userRepository;

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

    @GetMapping
    public ResponseEntity<User> login(@RequestParam String email, @RequestParam String hash,
                                       HttpServletRequest req) {
        Optional<UserEntity> user = userRepository.findByEmailAndPassword(email, hash);
        if (user.isPresent()) {
            LOGGER.info("User erfolgreich angemeldet: {}", email);
            return ResponseEntity.ok(user.get().toUser());
        } else {
            return ResponseEntity.noContent().build();
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity<User> get(@PathVariable UUID userId) {
        return userRepository.findById(userId)
                .map(entity -> ResponseEntity.ok(entity.toUser()))
                .orElse(ResponseEntity.noContent().build());
    }
}
