package com.social.media.service;

import com.social.media.dto.UserCredentialsDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Service interface for managing user credentials and security
 */
public interface UserCredentialsService {
    
    // Basic CRUD operations
    
    /**
     * Create new user credentials
     */
    UserCredentialsDto create(UserCredentialsDto dto);
    
    /**
     * Update existing user credentials
     */
    UserCredentialsDto update(Long userId, UserCredentialsDto dto);
    
    /**
     * Find user credentials by user ID
     */
    Optional<UserCredentialsDto> findByUserId(Long userId);
    
    /**
     * Get all user credentials with pagination
     */
    Page<UserCredentialsDto> findAll(Pageable pageable);
    
    /**
     * Delete user credentials
     */
    void delete(Long userId);
    
    // Authentication and security operations
    
    /**
     * Authenticate user with username/password
     */
    boolean authenticate(Long userId, String rawPassword);
    
    /**
     * Record successful login
     */
    void recordSuccessfulLogin(Long userId);
    
    /**
     * Record failed login attempt
     */
    void recordFailedLoginAttempt(Long userId);
    
    /**
     * Check if account is locked
     */
    boolean isAccountLocked(Long userId);
    
    /**
     * Lock account for specified duration
     */
    void lockAccount(Long userId, int lockoutMinutes);
    
    /**
     * Lock account permanently
     */
    void lockAccountPermanently(Long userId);
    
    /**
     * Unlock account
     */
    void unlockAccount(Long userId);
    
    /**
     * Reset failed login attempts
     */
    void resetFailedAttempts(Long userId);
    
    // Password management
    
    /**
     * Change user password
     */
    void changePassword(Long userId, String currentPassword, String newPassword);
    
    /**
     * Reset password with admin privileges (no current password required)
     */
    void resetPasswordByAdmin(Long userId, String newPassword);
    
    /**
     * Generate and set password reset token
     */
    String generatePasswordResetToken(Long userId, int expirationHours);
    
    /**
     * Validate password reset token
     */
    boolean validatePasswordResetToken(String token);
    
    /**
     * Reset password using token
     */
    boolean resetPasswordWithToken(String token, String newPassword);
    
    /**
     * Clear password reset token
     */
    void clearPasswordResetToken(Long userId);
    
    /**
     * Check if password needs to be changed (based on age)
     */
    boolean needsPasswordChange(Long userId, int maxAgeInDays);
    
    // Email verification
    
    /**
     * Generate and set email verification token
     */
    String generateEmailVerificationToken(Long userId);
    
    /**
     * Validate email verification token
     */
    boolean validateEmailVerificationToken(String token);
    
    /**
     * Mark email as verified and clear token
     */
    boolean verifyEmailWithToken(String token);
    
    /**
     * Clear email verification token
     */
    void clearEmailVerificationToken(Long userId);
    
    // Two-factor authentication
    
    /**
     * Enable two-factor authentication
     */
    void enableTwoFactor(Long userId);
    
    /**
     * Disable two-factor authentication
     */
    void disableTwoFactor(Long userId);
    
    /**
     * Check if two-factor authentication is enabled
     */
    boolean isTwoFactorEnabled(Long userId);
    
    // Security queries and analysis
    
    /**
     * Find accounts with failed login attempts
     */
    List<UserCredentialsDto> findAccountsWithFailedAttempts();
    
    /**
     * Find locked accounts
     */
    List<UserCredentialsDto> findLockedAccounts();
    
    /**
     * Find permanently locked accounts
     */
    List<UserCredentialsDto> findPermanentlyLockedAccounts();
    
    /**
     * Find accounts with pending password resets
     */
    List<UserCredentialsDto> findAccountsWithPendingPasswordReset();
    
    /**
     * Find expired password reset tokens
     */
    List<UserCredentialsDto> findExpiredPasswordResetTokens();
    
    /**
     * Find accounts with pending email verification
     */
    List<UserCredentialsDto> findAccountsWithPendingEmailVerification();
    
    /**
     * Find accounts with two-factor authentication enabled
     */
    List<UserCredentialsDto> findAccountsWithTwoFactorEnabled();
    
    /**
     * Find accounts with recent login activity
     */
    List<UserCredentialsDto> findAccountsWithRecentLogin(int daysBack);
    
    /**
     * Find inactive accounts
     */
    List<UserCredentialsDto> findInactiveAccounts(int daysBack);
    
    /**
     * Find accounts with old passwords
     */
    List<UserCredentialsDto> findAccountsWithOldPasswords(int daysBack);
    
    /**
     * Find accounts needing security review
     */
    List<UserCredentialsDto> findAccountsNeedingSecurityReview();
    
    /**
     * Search credentials by security criteria
     */
    Page<UserCredentialsDto> searchBySecurityCriteria(
            boolean hasFailedAttempts,
            boolean isLocked,
            boolean hasTwoFactor,
            Boolean twoFactorEnabled,
            boolean hasRecentLogin,
            int recentLoginDays,
            Pageable pageable);
    
    // Bulk operations
    
    /**
     * Clear all expired password reset tokens
     */
    int clearExpiredPasswordResetTokens();
    
    /**
     * Unlock accounts where lockout period has expired
     */
    int unlockExpiredAccountLocks();
    
    /**
     * Reset failed attempts for unlocked accounts
     */
    int resetFailedAttemptsForUnlockedAccounts();
    
    /**
     * Bulk enable two-factor authentication for users
     */
    void bulkEnableTwoFactor(List<Long> userIds);
    
    /**
     * Bulk disable two-factor authentication for users
     */
    void bulkDisableTwoFactor(List<Long> userIds);
    
    /**
     * Bulk unlock accounts
     */
    void bulkUnlockAccounts(List<Long> userIds);
    
    // Statistics and analytics
    
    /**
     * Get security statistics summary
     */
    Map<String, Object> getSecurityStatistics();
    
    /**
     * Get detailed security analytics
     */
    Map<String, Object> getSecurityAnalytics(int daysPeriod);
    
    /**
     * Count accounts by security status
     */
    Map<String, Long> getSecurityStatusCounts();
    
    /**
     * Get failed login attempts statistics
     */
    Map<String, Object> getFailedLoginStatistics(int daysPeriod);
    
    /**
     * Get password management statistics
     */
    Map<String, Object> getPasswordStatistics();
    
    /**
     * Get two-factor authentication adoption statistics
     */
    Map<String, Object> getTwoFactorStatistics();
    
    // Maintenance operations
    
    /**
     * Perform routine security maintenance
     */
    Map<String, Integer> performSecurityMaintenance();
    
    /**
     * Generate security report for admin dashboard
     */
    Map<String, Object> generateSecurityReport();
    
    /**
     * Check and alert on security anomalies
     */
    List<String> checkSecurityAnomalies();
    
    // Password strength and policies
    
    /**
     * Validate password strength
     */
    boolean isPasswordStrong(String password);
    
    /**
     * Get password strength score (0-100)
     */
    int getPasswordStrengthScore(String password);
    
    /**
     * Check if password meets policy requirements
     */
    boolean meetsPasswordPolicy(String password);
    
    /**
     * Get password policy violations
     */
    List<String> getPasswordPolicyViolations(String password);
    
    // Token management
    
    /**
     * Check if password reset token exists and is valid
     */
    boolean isPasswordResetTokenValid(String token);
    
    /**
     * Check if email verification token exists and is valid
     */
    boolean isEmailVerificationTokenValid(String token);
    
    /**
     * Find user ID by password reset token
     */
    Optional<Long> findUserIdByPasswordResetToken(String token);
    
    /**
     * Find user ID by email verification token
     */
    Optional<Long> findUserIdByEmailVerificationToken(String token);
    
    // Audit and logging
    
    /**
     * Get security events for user
     */
    List<String> getSecurityEvents(Long userId, int daysPeriod);
    
    /**
     * Log security event
     */
    void logSecurityEvent(Long userId, String eventType, String description);
    
    // System health checks
    
    /**
     * Check system security health
     */
    Map<String, Object> checkSecurityHealth();
    
    /**
     * Get security recommendations
     */
    List<String> getSecurityRecommendations();
}
