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 3 – No consecutive sequential characters.
 * Password must NOT contain {@value #MAX_SEQ_LEN} or more characters that are
 * consecutively increasing or decreasing in ASCII value (e.g. {@code 1234}, {@code abcd}, {@code dcba}).
 */
public class NoSequentialCharsPasswordRule implements PasswordRule {

    /** Maximum allowed sequential-character run length (exclusive). */
    public static final int MAX_SEQ_LEN = 4;

    @Override
    public PasswordRuleResult validate(String password, PasswordRuleContext context) {
        int seqLen = 1;
        for (int i = 1; i < password.length(); i++) {
            int diff = password.charAt(i) - password.charAt(i - 1);
            if (diff == 1 || diff == -1) {
                seqLen++;
                if (seqLen >= MAX_SEQ_LEN) {
                    return PasswordRuleResult.fail(
                            "Password must not contain " + MAX_SEQ_LEN
                          + " or more consecutive sequential characters (e.g. 1234, abcd, dcba)");
                }
            } else {
                seqLen = 1;
            }
        }
        return PasswordRuleResult.ok();
    }

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

}
