package com.social.media.controller;

import com.social.media.dto.UserCredentialsDto;
import com.social.media.service.UserCredentialsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * REST Controller for User Credentials management
 */
@RestController
@RequestMapping("/api/v1/user-credentials")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "User Credentials", description = "User credentials and security management operations")
public class UserCredentialsController {
    
    private final UserCredentialsService userCredentialsService;
    
    @Operation(summary = "Create user credentials", description = "Create new user credentials")
    @ApiResponse(responseCode = "201", description = "User credentials created successfully")
    @ApiResponse(responseCode = "400", description = "Invalid input or credentials already exist")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER')")
    public ResponseEntity<UserCredentialsDto> createUserCredentials(
            @Valid @RequestBody UserCredentialsDto dto) {
        
        log.info("Creating user credentials for user ID: {}", dto.getUserId());
        UserCredentialsDto created = userCredentialsService.create(dto);
        return new ResponseEntity<>(created, HttpStatus.CREATED);
    }
    
    @Operation(summary = "Update user credentials", description = "Update existing user credentials")
    @ApiResponse(responseCode = "200", description = "User credentials updated successfully")
    @ApiResponse(responseCode = "404", description = "User credentials not found")
    @PutMapping("/{userId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER') or authentication.name == #userId.toString()")
    public ResponseEntity<UserCredentialsDto> updateUserCredentials(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @Valid @RequestBody UserCredentialsDto dto) {
        
        log.info("Updating user credentials for user ID: {}", userId);
        UserCredentialsDto updated = userCredentialsService.update(userId, dto);
        return ResponseEntity.ok(updated);
    }
    
    @Operation(summary = "Get user credentials", description = "Get user credentials by user ID")
    @ApiResponse(responseCode = "200", description = "User credentials found")
    @ApiResponse(responseCode = "404", description = "User credentials not found")
    @GetMapping("/{userId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER') or authentication.name == #userId.toString()")
    public ResponseEntity<UserCredentialsDto> getUserCredentials(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        Optional<UserCredentialsDto> credentials = userCredentialsService.findByUserId(userId);
        return credentials.map(ResponseEntity::ok)
                         .orElse(ResponseEntity.notFound().build());
    }
    
    @Operation(summary = "Get all user credentials", description = "Get paginated list of all user credentials")
    @ApiResponse(responseCode = "200", description = "User credentials retrieved successfully")
    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER')")
    public ResponseEntity<Page<UserCredentialsDto>> getAllUserCredentials(Pageable pageable) {
        Page<UserCredentialsDto> credentials = userCredentialsService.findAll(pageable);
        return ResponseEntity.ok(credentials);
    }
    
    @Operation(summary = "Delete user credentials", description = "Delete user credentials by user ID")
    @ApiResponse(responseCode = "204", description = "User credentials deleted successfully")
    @ApiResponse(responseCode = "404", description = "User credentials not found")
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> deleteUserCredentials(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Deleting user credentials for user ID: {}", userId);
        userCredentialsService.delete(userId);
        return ResponseEntity.noContent().build();
    }
    
    // Authentication endpoints
    
    @Operation(summary = "Authenticate user", description = "Authenticate user with password")
    @ApiResponse(responseCode = "200", description = "Authentication successful")
    @ApiResponse(responseCode = "401", description = "Authentication failed")
    @PostMapping("/{userId}/authenticate")
    @PreAuthorize("hasRole('ADMIN') or hasRole('AUTH_SERVICE') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, Boolean>> authenticateUser(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestBody Map<String, String> credentials) {
        
        String password = credentials.get("password");
        boolean authenticated = userCredentialsService.authenticate(userId, password);
        
        return ResponseEntity.ok(Map.of("authenticated", authenticated));
    }
    
    // Account locking endpoints
    
    @Operation(summary = "Check account lock status", description = "Check if account is locked")
    @ApiResponse(responseCode = "200", description = "Lock status retrieved")
    @GetMapping("/{userId}/locked")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, Boolean>> isAccountLocked(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        boolean locked = userCredentialsService.isAccountLocked(userId);
        return ResponseEntity.ok(Map.of("locked", locked));
    }
    
    @Operation(summary = "Lock account", description = "Lock user account for specified minutes")
    @ApiResponse(responseCode = "200", description = "Account locked successfully")
    @PostMapping("/{userId}/lock")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER')")
    public ResponseEntity<Map<String, String>> lockAccount(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestParam(defaultValue = "30") int lockoutMinutes) {
        
        log.info("Locking account for user ID: {} for {} minutes", userId, lockoutMinutes);
        userCredentialsService.lockAccount(userId, lockoutMinutes);
        return ResponseEntity.ok(Map.of("message", "Account locked for " + lockoutMinutes + " minutes"));
    }
    
    @Operation(summary = "Lock account permanently", description = "Permanently lock user account")
    @ApiResponse(responseCode = "200", description = "Account permanently locked")
    @PostMapping("/{userId}/lock-permanent")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, String>> lockAccountPermanently(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Permanently locking account for user ID: {}", userId);
        userCredentialsService.lockAccountPermanently(userId);
        return ResponseEntity.ok(Map.of("message", "Account permanently locked"));
    }
    
    @Operation(summary = "Unlock account", description = "Unlock user account")
    @ApiResponse(responseCode = "200", description = "Account unlocked successfully")
    @PostMapping("/{userId}/unlock")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER')")
    public ResponseEntity<Map<String, String>> unlockAccount(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Unlocking account for user ID: {}", userId);
        userCredentialsService.unlockAccount(userId);
        return ResponseEntity.ok(Map.of("message", "Account unlocked successfully"));
    }
    
    @Operation(summary = "Reset failed attempts", description = "Reset failed login attempts counter")
    @ApiResponse(responseCode = "200", description = "Failed attempts reset successfully")
    @PostMapping("/{userId}/reset-failed-attempts")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER')")
    public ResponseEntity<Map<String, String>> resetFailedAttempts(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Resetting failed attempts for user ID: {}", userId);
        userCredentialsService.resetFailedAttempts(userId);
        return ResponseEntity.ok(Map.of("message", "Failed attempts reset successfully"));
    }
    
    // Password management endpoints
    
    @Operation(summary = "Change password", description = "Change user password")
    @ApiResponse(responseCode = "200", description = "Password changed successfully")
    @ApiResponse(responseCode = "400", description = "Invalid current password or new password policy violation")
    @PostMapping("/{userId}/change-password")
    @PreAuthorize("hasRole('ADMIN') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, String>> changePassword(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestBody Map<String, String> passwords) {
        
        String currentPassword = passwords.get("currentPassword");
        String newPassword = passwords.get("newPassword");
        
        log.info("Changing password for user ID: {}", userId);
        userCredentialsService.changePassword(userId, currentPassword, newPassword);
        return ResponseEntity.ok(Map.of("message", "Password changed successfully"));
    }
    
    @Operation(summary = "Reset password by admin", description = "Admin reset user password")
    @ApiResponse(responseCode = "200", description = "Password reset successfully")
    @ApiResponse(responseCode = "400", description = "New password policy violation")
    @PostMapping("/{userId}/reset-password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, String>> resetPasswordByAdmin(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestBody Map<String, String> request) {
        
        String newPassword = request.get("newPassword");
        
        log.info("Admin resetting password for user ID: {}", userId);
        userCredentialsService.resetPasswordByAdmin(userId, newPassword);
        return ResponseEntity.ok(Map.of("message", "Password reset successfully"));
    }
    
    @Operation(summary = "Check password age", description = "Check if password needs to be changed")
    @ApiResponse(responseCode = "200", description = "Password age status retrieved")
    @GetMapping("/{userId}/password-age")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, Boolean>> needsPasswordChange(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestParam(defaultValue = "90") int maxAgeInDays) {
        
        boolean needsChange = userCredentialsService.needsPasswordChange(userId, maxAgeInDays);
        return ResponseEntity.ok(Map.of("needsChange", needsChange));
    }
    
    // Password reset token endpoints
    
    @Operation(summary = "Generate password reset token", description = "Generate password reset token")
    @ApiResponse(responseCode = "200", description = "Reset token generated successfully")
    @PostMapping("/{userId}/password-reset-token")
    @PreAuthorize("hasRole('ADMIN') or hasRole('AUTH_SERVICE')")
    public ResponseEntity<Map<String, String>> generatePasswordResetToken(
            @Parameter(description = "User ID") @PathVariable Long userId,
            @RequestParam(defaultValue = "24") int expirationHours) {
        
        log.info("Generating password reset token for user ID: {}", userId);
        String token = userCredentialsService.generatePasswordResetToken(userId, expirationHours);
        return ResponseEntity.ok(Map.of("token", token, "expirationHours", String.valueOf(expirationHours)));
    }
    
    @Operation(summary = "Validate password reset token", description = "Validate password reset token")
    @ApiResponse(responseCode = "200", description = "Token validation result")
    @GetMapping("/password-reset-token/{token}/validate")
    public ResponseEntity<Map<String, Boolean>> validatePasswordResetToken(
            @Parameter(description = "Reset token") @PathVariable String token) {
        
        boolean valid = userCredentialsService.validatePasswordResetToken(token);
        return ResponseEntity.ok(Map.of("valid", valid));
    }
    
    @Operation(summary = "Reset password with token", description = "Reset password using reset token")
    @ApiResponse(responseCode = "200", description = "Password reset successfully")
    @ApiResponse(responseCode = "400", description = "Invalid token or password policy violation")
    @PostMapping("/password-reset-token/{token}/reset")
    public ResponseEntity<Map<String, String>> resetPasswordWithToken(
            @Parameter(description = "Reset token") @PathVariable String token,
            @RequestBody Map<String, String> request) {
        
        String newPassword = request.get("newPassword");
        
        log.info("Resetting password with token");
        boolean success = userCredentialsService.resetPasswordWithToken(token, newPassword);
        
        if (success) {
            return ResponseEntity.ok(Map.of("message", "Password reset successfully"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("error", "Invalid or expired token"));
        }
    }
    
    @Operation(summary = "Clear password reset token", description = "Clear password reset token")
    @ApiResponse(responseCode = "200", description = "Reset token cleared successfully")
    @DeleteMapping("/{userId}/password-reset-token")
    @PreAuthorize("hasRole('ADMIN') or hasRole('AUTH_SERVICE')")
    public ResponseEntity<Map<String, String>> clearPasswordResetToken(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Clearing password reset token for user ID: {}", userId);
        userCredentialsService.clearPasswordResetToken(userId);
        return ResponseEntity.ok(Map.of("message", "Reset token cleared successfully"));
    }
    
    // Email verification endpoints
    
    @Operation(summary = "Generate email verification token", description = "Generate email verification token")
    @ApiResponse(responseCode = "200", description = "Verification token generated successfully")
    @PostMapping("/{userId}/email-verification-token")
    @PreAuthorize("hasRole('ADMIN') or hasRole('AUTH_SERVICE') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, String>> generateEmailVerificationToken(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Generating email verification token for user ID: {}", userId);
        String token = userCredentialsService.generateEmailVerificationToken(userId);
        return ResponseEntity.ok(Map.of("token", token));
    }
    
    @Operation(summary = "Validate email verification token", description = "Validate email verification token")
    @ApiResponse(responseCode = "200", description = "Token validation result")
    @GetMapping("/email-verification-token/{token}/validate")
    public ResponseEntity<Map<String, Boolean>> validateEmailVerificationToken(
            @Parameter(description = "Verification token") @PathVariable String token) {
        
        boolean valid = userCredentialsService.validateEmailVerificationToken(token);
        return ResponseEntity.ok(Map.of("valid", valid));
    }
    
    @Operation(summary = "Verify email with token", description = "Verify email using verification token")
    @ApiResponse(responseCode = "200", description = "Email verified successfully")
    @ApiResponse(responseCode = "400", description = "Invalid token")
    @PostMapping("/email-verification-token/{token}/verify")
    public ResponseEntity<Map<String, String>> verifyEmailWithToken(
            @Parameter(description = "Verification token") @PathVariable String token) {
        
        log.info("Verifying email with token");
        boolean success = userCredentialsService.verifyEmailWithToken(token);
        
        if (success) {
            return ResponseEntity.ok(Map.of("message", "Email verified successfully"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("error", "Invalid token"));
        }
    }
    
    @Operation(summary = "Clear email verification token", description = "Clear email verification token")
    @ApiResponse(responseCode = "200", description = "Verification token cleared successfully")
    @DeleteMapping("/{userId}/email-verification-token")
    @PreAuthorize("hasRole('ADMIN') or hasRole('AUTH_SERVICE')")
    public ResponseEntity<Map<String, String>> clearEmailVerificationToken(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Clearing email verification token for user ID: {}", userId);
        userCredentialsService.clearEmailVerificationToken(userId);
        return ResponseEntity.ok(Map.of("message", "Verification token cleared successfully"));
    }
    
    // Two-factor authentication endpoints
    
    @Operation(summary = "Enable two-factor authentication", description = "Enable 2FA for user")
    @ApiResponse(responseCode = "200", description = "Two-factor authentication enabled")
    @PostMapping("/{userId}/two-factor/enable")
    @PreAuthorize("hasRole('ADMIN') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, String>> enableTwoFactor(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Enabling two-factor authentication for user ID: {}", userId);
        userCredentialsService.enableTwoFactor(userId);
        return ResponseEntity.ok(Map.of("message", "Two-factor authentication enabled"));
    }
    
    @Operation(summary = "Disable two-factor authentication", description = "Disable 2FA for user")
    @ApiResponse(responseCode = "200", description = "Two-factor authentication disabled")
    @PostMapping("/{userId}/two-factor/disable")
    @PreAuthorize("hasRole('ADMIN') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, String>> disableTwoFactor(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        log.info("Disabling two-factor authentication for user ID: {}", userId);
        userCredentialsService.disableTwoFactor(userId);
        return ResponseEntity.ok(Map.of("message", "Two-factor authentication disabled"));
    }
    
    @Operation(summary = "Check two-factor status", description = "Check if 2FA is enabled")
    @ApiResponse(responseCode = "200", description = "Two-factor status retrieved")
    @GetMapping("/{userId}/two-factor/status")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER_MANAGER') or authentication.name == #userId.toString()")
    public ResponseEntity<Map<String, Boolean>> isTwoFactorEnabled(
            @Parameter(description = "User ID") @PathVariable Long userId) {
        
        boolean enabled = userCredentialsService.isTwoFactorEnabled(userId);
        return ResponseEntity.ok(Map.of("enabled", enabled));
    }
    
    // Security analysis endpoints
    
    @Operation(summary = "Get accounts with failed attempts", description = "Get accounts with failed login attempts")
    @ApiResponse(responseCode = "200", description = "Accounts with failed attempts retrieved")
    @GetMapping("/security/failed-attempts")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getAccountsWithFailedAttempts() {
        List<UserCredentialsDto> accounts = userCredentialsService.findAccountsWithFailedAttempts();
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get locked accounts", description = "Get all locked accounts")
    @ApiResponse(responseCode = "200", description = "Locked accounts retrieved")
    @GetMapping("/security/locked")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getLockedAccounts() {
        List<UserCredentialsDto> accounts = userCredentialsService.findLockedAccounts();
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get permanently locked accounts", description = "Get permanently locked accounts")
    @ApiResponse(responseCode = "200", description = "Permanently locked accounts retrieved")
    @GetMapping("/security/permanently-locked")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getPermanentlyLockedAccounts() {
        List<UserCredentialsDto> accounts = userCredentialsService.findPermanentlyLockedAccounts();
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get accounts with two-factor enabled", description = "Get accounts with 2FA enabled")
    @ApiResponse(responseCode = "200", description = "Accounts with 2FA retrieved")
    @GetMapping("/security/two-factor-enabled")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getAccountsWithTwoFactorEnabled() {
        List<UserCredentialsDto> accounts = userCredentialsService.findAccountsWithTwoFactorEnabled();
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get recently active accounts", description = "Get accounts with recent login activity")
    @ApiResponse(responseCode = "200", description = "Recently active accounts retrieved")
    @GetMapping("/security/recent-activity")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getAccountsWithRecentActivity(
            @RequestParam(defaultValue = "30") int daysBack) {
        
        List<UserCredentialsDto> accounts = userCredentialsService.findAccountsWithRecentLogin(daysBack);
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get inactive accounts", description = "Get inactive accounts")
    @ApiResponse(responseCode = "200", description = "Inactive accounts retrieved")
    @GetMapping("/security/inactive")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getInactiveAccounts(
            @RequestParam(defaultValue = "90") int daysBack) {
        
        List<UserCredentialsDto> accounts = userCredentialsService.findInactiveAccounts(daysBack);
        return ResponseEntity.ok(accounts);
    }
    
    @Operation(summary = "Get accounts with old passwords", description = "Get accounts with old passwords")
    @ApiResponse(responseCode = "200", description = "Accounts with old passwords retrieved")
    @GetMapping("/security/old-passwords")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<UserCredentialsDto>> getAccountsWithOldPasswords(
            @RequestParam(defaultValue = "90") int daysBack) {
        
        List<UserCredentialsDto> accounts = userCredentialsService.findAccountsWithOldPasswords(daysBack);
        return ResponseEntity.ok(accounts);
    }
    
    // Bulk operations endpoints
    
    @Operation(summary = "Bulk enable two-factor", description = "Enable 2FA for multiple users")
    @ApiResponse(responseCode = "200", description = "Bulk two-factor enable completed")
    @PostMapping("/bulk/two-factor/enable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, String>> bulkEnableTwoFactor(
            @RequestBody List<Long> userIds) {
        
        log.info("Bulk enabling two-factor authentication for {} users", userIds.size());
        userCredentialsService.bulkEnableTwoFactor(userIds);
        return ResponseEntity.ok(Map.of("message", "Two-factor authentication enabled for " + userIds.size() + " users"));
    }
    
    @Operation(summary = "Bulk disable two-factor", description = "Disable 2FA for multiple users")
    @ApiResponse(responseCode = "200", description = "Bulk two-factor disable completed")
    @PostMapping("/bulk/two-factor/disable")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, String>> bulkDisableTwoFactor(
            @RequestBody List<Long> userIds) {
        
        log.info("Bulk disabling two-factor authentication for {} users", userIds.size());
        userCredentialsService.bulkDisableTwoFactor(userIds);
        return ResponseEntity.ok(Map.of("message", "Two-factor authentication disabled for " + userIds.size() + " users"));
    }
    
    @Operation(summary = "Bulk unlock accounts", description = "Unlock multiple accounts")
    @ApiResponse(responseCode = "200", description = "Bulk unlock completed")
    @PostMapping("/bulk/unlock")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, String>> bulkUnlockAccounts(
            @RequestBody List<Long> userIds) {
        
        log.info("Bulk unlocking {} accounts", userIds.size());
        userCredentialsService.bulkUnlockAccounts(userIds);
        return ResponseEntity.ok(Map.of("message", "Unlocked " + userIds.size() + " accounts"));
    }
    
    // Statistics and analytics endpoints
    
    @Operation(summary = "Get security statistics", description = "Get security statistics overview")
    @ApiResponse(responseCode = "200", description = "Security statistics retrieved")
    @GetMapping("/statistics")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Object>> getSecurityStatistics() {
        Map<String, Object> statistics = userCredentialsService.getSecurityStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    @Operation(summary = "Get security analytics", description = "Get detailed security analytics")
    @ApiResponse(responseCode = "200", description = "Security analytics retrieved")
    @GetMapping("/analytics")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Object>> getSecurityAnalytics(
            @RequestParam(defaultValue = "30") int daysPeriod) {
        
        Map<String, Object> analytics = userCredentialsService.getSecurityAnalytics(daysPeriod);
        return ResponseEntity.ok(analytics);
    }
    
    @Operation(summary = "Get security status counts", description = "Get security status counts")
    @ApiResponse(responseCode = "200", description = "Security status counts retrieved")
    @GetMapping("/status-counts")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Long>> getSecurityStatusCounts() {
        Map<String, Long> counts = userCredentialsService.getSecurityStatusCounts();
        return ResponseEntity.ok(counts);
    }
    
    @Operation(summary = "Get two-factor statistics", description = "Get two-factor authentication statistics")
    @ApiResponse(responseCode = "200", description = "Two-factor statistics retrieved")
    @GetMapping("/statistics/two-factor")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Object>> getTwoFactorStatistics() {
        Map<String, Object> statistics = userCredentialsService.getTwoFactorStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    // Maintenance endpoints
    
    @Operation(summary = "Perform security maintenance", description = "Perform routine security maintenance")
    @ApiResponse(responseCode = "200", description = "Security maintenance completed")
    @PostMapping("/maintenance")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Integer>> performSecurityMaintenance() {
        log.info("Performing security maintenance");
        Map<String, Integer> results = userCredentialsService.performSecurityMaintenance();
        return ResponseEntity.ok(results);
    }
    
    @Operation(summary = "Generate security report", description = "Generate comprehensive security report")
    @ApiResponse(responseCode = "200", description = "Security report generated")
    @GetMapping("/report")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Object>> generateSecurityReport() {
        Map<String, Object> report = userCredentialsService.generateSecurityReport();
        return ResponseEntity.ok(report);
    }
    
    @Operation(summary = "Check security anomalies", description = "Check for security anomalies")
    @ApiResponse(responseCode = "200", description = "Security anomalies check completed")
    @GetMapping("/anomalies")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<String>> checkSecurityAnomalies() {
        List<String> anomalies = userCredentialsService.checkSecurityAnomalies();
        return ResponseEntity.ok(anomalies);
    }
    
    @Operation(summary = "Check security health", description = "Check overall security health")
    @ApiResponse(responseCode = "200", description = "Security health status retrieved")
    @GetMapping("/health")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<Map<String, Object>> checkSecurityHealth() {
        Map<String, Object> health = userCredentialsService.checkSecurityHealth();
        return ResponseEntity.ok(health);
    }
    
    @Operation(summary = "Get security recommendations", description = "Get security recommendations")
    @ApiResponse(responseCode = "200", description = "Security recommendations retrieved")
    @GetMapping("/recommendations")
    @PreAuthorize("hasRole('ADMIN') or hasRole('SECURITY_ANALYST')")
    public ResponseEntity<List<String>> getSecurityRecommendations() {
        List<String> recommendations = userCredentialsService.getSecurityRecommendations();
        return ResponseEntity.ok(recommendations);
    }
    
    // Password policy endpoints
    
    @Operation(summary = "Check password strength", description = "Check password strength")
    @ApiResponse(responseCode = "200", description = "Password strength checked")
    @PostMapping("/password/check-strength")
    public ResponseEntity<Map<String, Object>> checkPasswordStrength(
            @RequestBody Map<String, String> request) {
        
        String password = request.get("password");
        boolean isStrong = userCredentialsService.isPasswordStrong(password);
        int score = userCredentialsService.getPasswordStrengthScore(password);
        
        Map<String, Object> result = Map.of(
            "isStrong", isStrong,
            "score", score,
            "maxScore", 100
        );
        
        return ResponseEntity.ok(result);
    }
    
    @Operation(summary = "Validate password policy", description = "Validate password against policy")
    @ApiResponse(responseCode = "200", description = "Password policy validation completed")
    @PostMapping("/password/validate-policy")
    public ResponseEntity<Map<String, Object>> validatePasswordPolicy(
            @RequestBody Map<String, String> request) {
        
        String password = request.get("password");
        boolean meetsPolicy = userCredentialsService.meetsPasswordPolicy(password);
        List<String> violations = userCredentialsService.getPasswordPolicyViolations(password);
        
        Map<String, Object> result = Map.of(
            "meetsPolicy", meetsPolicy,
            "violations", violations
        );
        
        return ResponseEntity.ok(result);
    }
}
