package de.oaa.xxx.user;

import de.oaa.xxx.admin.AdminRepository;
import de.oaa.xxx.config.JwtService;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.security.Principal;
import java.time.Duration;
import java.util.UUID;

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

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

    record LoginRequest(String email, String password) {}

    private final UserRepository userRepository;
    private final JwtService jwtService;
    private final PasswordEncoder passwordEncoder;
    private final AdminRepository adminRepository;
    private final UserService userService;

    public LoginController(UserRepository userRepository, JwtService jwtService, PasswordEncoder passwordEncoder, AdminRepository adminRepository, UserService userService) {
        this.userRepository = userRepository;
        this.jwtService = jwtService;
        this.passwordEncoder = passwordEncoder;
        this.adminRepository = adminRepository;
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<User> login(@RequestBody LoginRequest request, HttpServletResponse response) {
        var userOpt = userRepository.findByEmail(request.email());
        if (userOpt.isPresent() && passwordEncoder.matches(request.password(), userOpt.get().getPassword())) {
            UserEntity user = userOpt.get();
            LOGGER.info("User erfolgreich angemeldet: {}", request.email());
            String token = jwtService.generateToken(user.getEmail(), user.getName());
            ResponseCookie cookie = ResponseCookie.from("jwt", token)
                    .httpOnly(true)
                    .sameSite("Strict")
                    .path("/")
                    .maxAge(Duration.ofHours(24))
                    .build();
            response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
            User u = user.toUser();
            u.setAdmin(adminRepository.existsByUserId(user.getUserId()));
            return ResponseEntity.ok(u);
        } else {
            return ResponseEntity.noContent().build();
        }
    }

    @GetMapping("/me")
    public ResponseEntity<User> me(Principal principal) {
        if (principal == null) {
            return ResponseEntity.status(401).build();
        }
        UserEntity entity = userService.requireUser(principal);
        User u = entity.toUser();
        u.setAdmin(adminRepository.existsByUserId(entity.getUserId()));
        return ResponseEntity.ok(u);
    }

    @GetMapping("/logout")
    public void logout(HttpServletResponse response) throws java.io.IOException {
        ResponseCookie cookie = ResponseCookie.from("jwt", "")
                .httpOnly(true)
                .sameSite("Strict")
                .path("/")
                .maxAge(0)
                .build();
        response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        response.sendRedirect("/");
    }

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