package io.teaql.provider.jdbc;
import org.junit.Test;
import org.sqlite.SQLiteDataSource;
import javax.sql.DataSource;
import java.lang.reflect.*;
import java.nio.file.*;
import java.sql.*;
import java.util.*;
import static org.junit.Assert.*;

public class JdbcCommitFailureTest {
 @Test public void sqliteCommitBusyRollsBackBeforeConnectionReleaseAndCanRetry() throws Exception {
  Path file=Files.createTempFile("teaql-commit-busy-", ".sqlite");
  SQLiteDataSource dataSource=new SQLiteDataSource();dataSource.setUrl("jdbc:sqlite:"+file+"?busy_timeout=25");
  JdbcSqlExecutor executor=new JdbcSqlExecutor(dataSource);
  try(Connection reader=dataSource.getConnection()){
   executor.execute("CREATE TABLE order_probe(id INTEGER PRIMARY KEY, amount INTEGER)");executor.update("INSERT INTO order_probe VALUES(1,10)",new Object[0]);
   try{
    executor.executeInTransaction(()->{
     executor.update("UPDATE order_probe SET amount=20 WHERE id=1",new Object[0]);
     try{reader.setAutoCommit(false);try(var statement=reader.createStatement();var rows=statement.executeQuery("SELECT * FROM order_probe")){assertTrue(rows.next());assertEquals(10,rows.getInt("amount"));}}catch(SQLException e){throw new RuntimeException(e);}
    });fail("Native COMMIT must fail while the reader retains its SHARED lock");
   }catch(RuntimeException failure){assertTrue(failure.getCause() instanceof SQLException);assertTrue(failure.getCause().getMessage().toLowerCase().contains("locked"));}
   assertFalse(executor.hasActiveTransaction());reader.rollback();reader.setAutoCommit(true);
   assertEquals(10,((Number)executor.queryForList("SELECT amount FROM order_probe WHERE id=1",new Object[0]).get(0).get("amount")).intValue());
   executor.executeInTransaction(()->executor.update("UPDATE order_probe SET amount=30 WHERE id=1",new Object[0]));
   assertEquals(30,((Number)executor.queryForList("SELECT amount FROM order_probe WHERE id=1",new Object[0]).get(0).get("amount")).intValue());
  }finally{Files.deleteIfExists(file);}
 }
 @Test public void rollbackFailureCannotReplaceCommitFailureOrEnableAutoCommit() throws Exception {
  SQLException commitFailure=new SQLException("native commit failure"),rollbackFailure=new SQLException("native rollback failure");List<String> calls=new ArrayList<>();
  Connection connection=(Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},(p,m,a)->switch(m.getName()){
   case "setAutoCommit"->{calls.add("auto:"+a[0]);yield null;}
   case "commit"->{calls.add("commit");throw commitFailure;}
   case "rollback"->{calls.add("rollback");throw rollbackFailure;}
   case "close"->{calls.add("close");yield null;}
   default->throw new UnsupportedOperationException(m.getName());
  });
  DataSource source=(DataSource)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{DataSource.class},(p,m,a)->{if(m.getName().equals("getConnection"))return connection;throw new UnsupportedOperationException(m.getName());});
  JdbcSqlExecutor executor=new JdbcSqlExecutor(source);
  try{executor.executeInTransaction(()->{});fail("Must retain commit failure");}catch(RuntimeException error){assertSame(commitFailure,error.getCause());assertArrayEquals(new Throwable[]{rollbackFailure},commitFailure.getSuppressed());}
  assertEquals(List.of("auto:false","commit","rollback","close"),calls);assertFalse(executor.hasActiveTransaction());
 }
 @Test public void cancellationKeepsItsIdentityWhenRollbackAlsoFails() throws Exception {
  var cancellation=new java.util.concurrent.CancellationException("cancel request");SQLException cleanup=new SQLException("rollback unavailable");List<String> calls=new ArrayList<>();
  Connection connection=(Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},(p,m,a)->switch(m.getName()){
   case "setAutoCommit"->null;case "rollback"->{calls.add("rollback");throw cleanup;}case "close"->{calls.add("close");yield null;}default->throw new UnsupportedOperationException(m.getName());
  });
  DataSource source=(DataSource)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{DataSource.class},(p,m,a)->{if(m.getName().equals("getConnection"))return connection;throw new UnsupportedOperationException(m.getName());});
  JdbcSqlExecutor executor=new JdbcSqlExecutor(source);try{executor.executeInTransaction(()->{throw cancellation;});fail("Cancellation expected");}catch(java.util.concurrent.CancellationException actual){assertSame(cancellation,actual);assertArrayEquals(new Throwable[]{cleanup},actual.getSuppressed());}assertEquals(List.of("rollback","close"),calls);assertFalse(executor.hasActiveTransaction());
 }
}
