package hr.com.port.ips.eracun.resilience.mer;

public final class MerSoftFailContext {

    public static final class SoftFailInfo {
        public final MerTriageHelper.Category category;
        public final Integer httpStatus;
        public final String opKey;
        public final long occurredAtMs;
        public final String message;
        public final String exceptionClass;

        SoftFailInfo(MerTriageHelper.Category category, Integer httpStatus,
                     String opKey, long occurredAtMs, String message, String exceptionClass) {
            this.category = category;
            this.httpStatus = httpStatus;
            this.opKey = opKey;
            this.occurredAtMs = occurredAtMs;
            this.message = message;
            this.exceptionClass = exceptionClass;
        }
    }

    private static final ThreadLocal<SoftFailInfo> TL = new ThreadLocal<SoftFailInfo>();

    private MerSoftFailContext() {}

    public static void clear() { TL.remove(); }

    public static void markSoftFail(MerTriageHelper.Category category,
                                    Integer httpStatus,
                                    String opKey,
                                    String message,
                                    Exception ex) {
        TL.set(new SoftFailInfo(
                category, httpStatus, opKey, System.currentTimeMillis(),
                message, ex != null ? ex.getClass().getName() : null
        ));
    }

    // MVP-light: dovoljan nam je boolean
    public static boolean wasSoftFail() { return TL.get() != null; }

    // Za kasnije, ako zatreba: detalji
    public static SoftFailInfo getInfo() { return TL.get(); }
	
	// === NOVO: granularni upit po ključu (opKey) ===
	public static boolean wasSoftFailFor(String opKey) {
		SoftFailInfo info = TL.get();
		if (info == null) return false;
		if (opKey == null) return false;
		return opKey.equals(info.opKey);
	}

	// === NOVO: overload za enum tip ===
	public static boolean wasSoftFailFor(MerApiCallType type) {
		return (type != null) && wasSoftFailFor(type.name());
	}

	// === (opcionalno) dohvat detalja samo ako se odnose na dati ključ ===
	public static SoftFailInfo getInfoIfOp(String opKey) {
		SoftFailInfo info = TL.get();
		return (info != null && opKey != null && opKey.equals(info.opKey)) ? info : null;
	}

	public static SoftFailInfo getInfoIfOp(MerApiCallType type) {
		return (type != null) ? getInfoIfOp(type.name()) : null;
	}	
}