package hr.com.port.ips.eracun.merapi.errors;

import hr.com.port.ips.eracun.provider.resilience.ProviderErrorAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

public final class MerErrorAdvice {
    private static final List<Rule> DEFAULT_RULES = new ArrayList<Rule>();
    private static final List<Rule> MER_RULES = new ArrayList<Rule>();

    static {
        // DEFAULT (vrijedi za sve)
        DEFAULT_RULES.add(new Rule("invalid username or password", ProviderErrorAction.FIX_CONFIG));
        DEFAULT_RULES.add(new Rule("integration software .* does not exist", ProviderErrorAction.FIX_CONFIG));
        DEFAULT_RULES.add(new Rule("root element is missing", ProviderErrorAction.VALIDATE_INPUT));
        DEFAULT_RULES.add(new Rule("unexpected character .* parsing", ProviderErrorAction.VALIDATE_INPUT));
        DEFAULT_RULES.add(new Rule("the supplied value is invalid", ProviderErrorAction.VALIDATE_INPUT));
        DEFAULT_RULES.add(new Rule("document status .* is not defined", ProviderErrorAction.VALIDATE_INPUT));

        // MER specifično
        MER_RULES.add(new Rule("sender or recipient organization not found", ProviderErrorAction.USE_EREPORTING));
        MER_RULES.add(new Rule("customer not registered in ams", ProviderErrorAction.USE_EREPORTING));
    }

    private MerErrorAdvice() {}

    /** provider: "MER" ili neki budući; null ⇒ koristi samo DEFAULT */
    public static ProviderErrorAction suggest(String provider, String message) {
        if (message == null) return ProviderErrorAction.DISPLAY_ONLY;
        String m = message.toLowerCase(Locale.ROOT);

        // Provider-ružle
        if ("MER".equalsIgnoreCase(provider)) {
            for (Rule r : MER_RULES) if (r.matches(m)) return r.action;
        }
        // Defaultne
        for (Rule r : DEFAULT_RULES) if (r.matches(m)) return r.action;

        // Nije pogođeno – default
        return ProviderErrorAction.DISPLAY_ONLY;
    }

    /** Omogućuje dinamičko dodavanje pravila (npr. iz properties/DB) */
    public static void addRule(String provider, String regex, ProviderErrorAction action) {
        Rule r = new Rule(regex, action);
        if ("MER".equalsIgnoreCase(provider)) MER_RULES.add(r);
        else DEFAULT_RULES.add(r);
    }

    private static final class Rule {
        private final Pattern p;
        private final ProviderErrorAction action;
        Rule(String regex, ProviderErrorAction action) { this.p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); this.action = action; }
        boolean matches(String msg) { return p.matcher(msg).find(); }
    }
}