import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.cache.transaction.TransactionAwareCacheManagerProxy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

public class CacheEvictFailure {
    static final String KEY = "p1";
    static final RuntimeException OFFLINE = new IllegalStateException("synthetic eviction failure");

    @Configuration
    @EnableCaching
    static class Config implements CachingConfigurer {
        final AtomicInteger handlerCalls = new AtomicInteger();
        @Bean Evictions evictions() { return new Evictions(); }

        @Bean @Override
        public CacheErrorHandler errorHandler() {
            return new SimpleCacheErrorHandler() {
                @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
                    expect(e, OFFLINE, "interceptor error identity");
                    expect(key, KEY, "interceptor error key");
                    handlerCalls.incrementAndGet();
                }
            };
        }
    }

    public static class Evictions {
        @CacheEvict(cacheNames = "prices", key = "#p0")
        public void updateCache(String productId) {}
    }

    record Case(String name, boolean aware, boolean fail, boolean rollback,
                int attemptsAtReturn, int attemptsAtEnd, int handled, boolean thrown,
                Integer cacheValue, int dbPrice) {}

    public static void main(String[] args) {
        for (var c : List.of(
                new Case("immediate failure, handler absorbs", false, true, false, 1, 1, 1, false, 10, 20),
                new Case("deferred failure, caller sees error", true, true, false, 0, 1, 0, true, 10, 20),
                new Case("deferred failure path, rollback", true, true, true, 0, 0, 0, false, 10, 10),
                new Case("deferred success control", true, false, false, 0, 1, 0, false, null, 20))) {
            run(c);
        }
    }

    static void run(Case c) {
        var ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:mem:cache_evict_failure;DB_CLOSE_DELAY=-1");
        var jdbc = new JdbcTemplate(ds);
        jdbc.execute("create table if not exists product (id varchar(20) primary key, price int)");
        jdbc.update("merge into product key(id) values (?, ?)", KEY, 10);
        var tx = new TransactionTemplate(new DataSourceTransactionManager(ds));
        var attempts = new AtomicInteger();
        var raw = new ConcurrentMapCache("prices") {
            @Override public void evict(Object key) {
                attempts.incrementAndGet();
                if (c.fail()) throw OFFLINE;
                super.evict(key);
            }
        };
        raw.put(KEY, 10);
        var manager = new SimpleCacheManager();
        manager.setCaches(List.of(raw));
        manager.initializeCaches();
        try (var ctx = new AnnotationConfigApplicationContext()) {
            ctx.registerBean("cacheManager", CacheManager.class,
                () -> c.aware() ? new TransactionAwareCacheManagerProxy(manager) : manager);
            ctx.register(Config.class);
            ctx.refresh();
            boolean thrown = false;
            try {
                tx.executeWithoutResult(status -> {
                    expect(jdbc.update("update product set price = 20 where id = ?", KEY), 1, "updated rows");
                    ctx.getBean(Evictions.class).updateCache(KEY);
                    expect(attempts.get(), c.attemptsAtReturn(), "eviction attempts at method return");
                    expect(raw.get(KEY, Integer.class), 10, "cache before transaction completion");
                    if (c.rollback()) status.setRollbackOnly();
                });
            } catch (RuntimeException e) {
                expect(e, OFFLINE, "exception seen outside transaction");
                thrown = true;
            }
            int price = jdbc.queryForObject("select price from product where id = ?", Integer.class, KEY);
            Integer cached = raw.get(KEY, Integer.class);
            int handled = ctx.getBean(Config.class).handlerCalls.get();
            expect(price, c.dbPrice(), "database state after transaction exits");
            expect(cached, c.cacheValue(), "cache state after transaction exits");
            expect(handled, c.handled(), "interceptor handler calls");
            expect(attempts.get(), c.attemptsAtEnd(), "total eviction attempts");
            expect(thrown, c.thrown(), "caller saw cache failure");
            System.out.printf("PASS %s: database=%d, cache=%s, evictions=%d, handler=%d, callerError=%s%n",
                c.name(), price, cached, attempts.get(), handled, thrown);
        } catch (AssertionError e) {
            throw new AssertionError(c.name() + ": " + e.getMessage(), e);
        }
    }

    static void expect(Object actual, Object expected, String label) {
        if (!Objects.equals(actual, expected))
            throw new AssertionError(label + ": expected " + expected + " but got " + actual);
    }
}
