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;

/**
 * Rule 4 – No consecutive repeated characters.
 * Password must NOT contain {@value #MAX_REP_LEN} or more identical characters in a row
 * (e.g. {@code aaaa}, {@code 1111}, {@code 111222}).
 */
public class NoRepeatedCharsPasswordRule implements PasswordRule {

    /** Maximum allowed run of identical consecutive characters (exclusive). */
    public static final int MAX_REP_LEN = 4;

    @Override
    public PasswordRuleResult validate(String password, PasswordRuleContext context) {
        int repLen = 1;
        for (int i = 1; i < password.length(); i++) {
            if (password.charAt(i) == password.charAt(i - 1)) {
                repLen++;
                if (repLen >= MAX_REP_LEN) {
                    return PasswordRuleResult.fail(
                            "Password must not contain " + MAX_REP_LEN
                          + " or more repeated identical characters (e.g. aaaa, 1111)");
                }
            } else {
                repLen = 1;
            }
        }
        return PasswordRuleResult.ok();
    }

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

}
