package de.oaa.xxx.user;

import de.oaa.xxx.config.JwtService;
import jakarta.servlet.http.HttpServletRequest;
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 java.util.Optional;
import java.util.UUID;

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

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

    private final UserRepository userRepository;
    private final JwtService jwtService;

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

    @GetMapping
    public ResponseEntity<String> 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);
            String token = jwtService.createToken(email, user.get().getUserId(), req.getRemoteAddr());
            return ResponseEntity.ok(token);
        } 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());
    }

    @GetMapping("/publickey")
    public ResponseEntity<String> getPublicKey() {
        return ResponseEntity.ok(jwtService.getPublicKeyBase64());
    }
}
