package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Supplier;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;

import static org.junit.Assert.assertNotEquals;


public class MultiTenantHibernateIntegrationTest {
    @Test
    public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () {
        SessionFactory sessionFactory;
        try {
            sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
            
            Session db1Session = sessionFactory
                .withOptions().tenantIdentifier("mydb1").openSession();
            
            initDb1(db1Session);
            
            Transaction transaction = db1Session.getTransaction();
            transaction.begin();
            Supplier supplierFromDB1 = (Supplier)db1Session.createCriteria(Supplier.class).list().get(0);
            transaction.commit();
            
            Session db2Session = sessionFactory
                .withOptions().tenantIdentifier("mydb2").openSession();
            
            initDb2(db2Session);
            db2Session.getTransaction().begin();
            Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
            db2Session.getTransaction().commit();
            
            System.out.println(supplierFromDB1);
            System.out.println(supplierFromDB2);
            
            assertNotEquals(supplierFromDB1, supplierFromDB2);   
        } catch (UnsupportedTenancyException e) {
            e.printStackTrace();
        }
    }



    private void initDb1(Session db1Session) {
        System.out.println("Init DB1");
        Transaction transaction = db1Session.getTransaction();
        transaction.begin();
        db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
        db1Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
        db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate();
        transaction.commit();
    }
    
    private void initDb2(Session db2Session) {
        System.out.println("Init DB2");
        Transaction transaction = db2Session.getTransaction();
        transaction.begin();
        db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
        db2Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
        db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate();
        transaction.commit();
    }
}
