import java.util.List;
import java.util.Objects;
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.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
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 CacheEvictTiming {
    private static final String KEY = "p1";

    @Configuration
    @EnableCaching
    static class Config {
        @Bean Evictions evictions() { return new Evictions(); }
    }

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

        @CacheEvict(cacheNames = "prices", key = "#p0", beforeInvocation = true)
        public void beforeCall(String productId) {}
    }

    record Scenario(String name, boolean aware, boolean early, boolean inTx,
                    boolean rollback, boolean cachedAfterReturn, boolean cachedAtEnd) {}

    public static void main(String[] args) {
        for (var scenario : List.of(
                new Scenario("plain + commit", false, false, true, false, false, false),
                new Scenario("plain + rollback", false, false, true, true, false, false),
                new Scenario("aware + commit", true, false, true, false, true, false),
                new Scenario("aware + rollback", true, false, true, true, true, true),
                new Scenario("aware + early + commit", true, true, true, false, false, false),
                new Scenario("aware + early + rollback", true, true, true, true, false, false),
                new Scenario("aware + no transaction", true, false, false, false, false, false))) {
            run(scenario);
        }
    }

    static void run(Scenario s) {
        var ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:mem:cache_evict_timing;DB_CLOSE_DELAY=-1");
        var jdbc = new JdbcTemplate(ds);
        jdbc.execute("create table if not exists product (id varchar(20) primary key, price int not null)");
        jdbc.update("merge into product key(id) values (?, ?)", KEY, 10);
        var tx = new TransactionTemplate(new DataSourceTransactionManager(ds));

        var rawManager = new ConcurrentMapCacheManager("prices");
        Cache rawCache = Objects.requireNonNull(rawManager.getCache("prices"));
        rawCache.put(KEY, 10);
        try (var ctx = new AnnotationConfigApplicationContext()) {
            ctx.registerBean("cacheManager", CacheManager.class,
                    () -> s.aware() ? new TransactionAwareCacheManagerProxy(rawManager) : rawManager);
            ctx.register(Config.class);
            ctx.refresh();
            var evictions = ctx.getBean(Evictions.class);
            Runnable method = () -> {
                expect(jdbc.update("update product set price = 20 where id = ?", KEY), 1, "rows");
                if (s.early()) evictions.beforeCall(KEY);
                else evictions.afterReturn(KEY);
                expect(rawCache.get(KEY) != null, s.cachedAfterReturn(), "cache at method return");
            };

            if (s.inTx()) {
                tx.executeWithoutResult(status -> {
                    method.run();
                    if (s.rollback()) status.setRollbackOnly();
                });
            } else {
                method.run();
            }

            expect(rawCache.get(KEY, Integer.class), s.cachedAtEnd() ? Integer.valueOf(10) : null,
                    "cache after completion");
            int price = jdbc.queryForObject("select price from product where id = ?", Integer.class, KEY);
            expect(price, s.rollback() ? 10 : 20, "database price after completion");
            System.out.printf("PASS %-27s cache at return=%s, cache at end=%s, db price=%d%n",
                    s.name(), s.cachedAfterReturn(), s.cachedAtEnd(), price);
        } catch (AssertionError e) {
            throw new AssertionError(s.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);
        }
    }
}
