package com.dji.sample.manage.service.password;

import com.dji.sample.manage.model.password.PasswordRule;
import com.dji.sample.manage.model.password.PasswordRuleContext;
import com.dji.sample.manage.model.password.PasswordRuleResult;
import org.springframework.util.StringUtils;

/**
 * Rule 6 – Similarity to personal information.
 * Password must NOT be similar to the user's username or contain the last 6 digits of their phone number.
 * Skipped when {@link PasswordRuleContext} is {@code null} or the relevant fields are blank.
 */
public class UserSimilarityPasswordRule implements PasswordRule {

    @Override
    public PasswordRuleResult validate(String password, PasswordRuleContext context) {
        if (context == null) {
            return PasswordRuleResult.ok();
        }

        String lower = password.toLowerCase();

        // Check username similarity
        if (StringUtils.hasText(context.getUsername())) {
            String uname = context.getUsername().toLowerCase();
            if (lower.contains(uname) || uname.contains(lower)) {
                return PasswordRuleResult.fail("Password must not be similar to your username");
            }
        }

        // Check phone number: forbid last 6 digits of phone appearing in the password
        if (StringUtils.hasText(context.getPhoneNumber())) {
            String phone = context.getPhoneNumber().replaceAll("\\D", "");
            if (phone.length() >= 6 && password.contains(phone.substring(phone.length() - 6))) {
                return PasswordRuleResult.fail("Password must not contain your phone number");
            }
        }

        return PasswordRuleResult.ok();
    }

    @Override
    public String getRuleName() {
        return "UserSimilarity";
    }

}
