package com.alterdekim.game.security;

import com.alterdekim.game.entity.User;
import com.alterdekim.game.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Optional;

@Slf4j
public class AuthenticationUtil {
    public static Optional<User> authProfile(UserService userService) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if( !authentication.isAuthenticated() ) return Optional.empty();
        Object o = authentication.getPrincipal();
        if( o.getClass().getSimpleName().equals("String") ) {
            return Optional.empty();
        }
        return Optional.of(userService.findByUsername(((org.springframework.security.core.userdetails.User) o).getUsername()));
    }

    public static Boolean hwIdAuth(User user, String token) {
        return new BCryptPasswordEncoder().matches(user.getId()+user.getPassword()+user.getUsername(), token);
    }

    public static String getToken(User user) {
        return new BCryptPasswordEncoder().encode(user.getId()+user.getPassword()+user.getUsername());
    }

    public static boolean checkCredentials(String username, String password) {
        return username.length() >= 3 &&
                username.length() <= 25 &&
                !username.matches("[^a-zA-Z0-9а-яА-Я-_]") &&
                password.length() >= 5 &&
                password.length() <= 128 &&
                password.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&+=]).{4,128}$");
    }
}
