package de.votian.services.controller;

import de.votian.services.dto.AuthLoginRequest;
import de.votian.services.dto.AuthResponse;
import de.votian.services.dto.AuthTotpRequest;
import de.votian.services.dto.ChangePasswordRequest;
import de.votian.services.dto.UserSessionDto;
import de.votian.services.service.AuthService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/login")
    public ResponseEntity<AuthResponse> login(@RequestBody AuthLoginRequest request) {
        return authService.login(request.getAccount(), request.getPassword())
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
    }

    @PostMapping("/verify-totp")
    public ResponseEntity<AuthResponse> verifyTotp(@RequestBody AuthTotpRequest request) {
        return authService.verifyTotp(request.getPendingToken(), request.getCode())
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
    }

    @GetMapping("/me")
    public ResponseEntity<UserSessionDto> me(Authentication authentication) {
        if (authentication == null || !(authentication.getPrincipal() instanceof UserSessionDto user)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(user);
    }

    @PostMapping("/change-password")
    public ResponseEntity<Map<String, Object>> changePassword(Authentication authentication,
                                                             @RequestBody ChangePasswordRequest request) {
        if (authentication == null || !(authentication.getPrincipal() instanceof UserSessionDto user)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        boolean changed = authService.changePassword(user.getUserId(),
                request.getCurrentPassword(),
                request.getNewPassword());
        if (!changed) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("changed", false, "message", "Aktuelles Passwort ist ungueltig."));
        }
        return ResponseEntity.ok(Map.of("changed", true));
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization) {
        if (authorization != null && authorization.startsWith("Bearer ")) {
            authService.logout(authorization.substring("Bearer ".length()).trim());
        }
        return ResponseEntity.ok().build();
    }
}
