package dst.ass1.jpa.tests;

import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertFalse;

import java.sql.SQLException;

import javax.persistence.PersistenceException;

import org.hibernate.PropertyValueException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import dst.ass1.jpa.ORMService;
import dst.ass1.jpa.model.IParticipant;
import dst.ass1.jpa.util.Constants;

/**
 * Tests the constraint for IParticipant email.
 */
public class Ass1_1_2_02Test {

    @Rule
    public ORMService orm = new ORMService();

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testUniqueConstraint() {
        new UniqueConstraintTester<>(() -> orm.getModelFactory().createParticipant(), e -> e.setEmail("unique@example.com"))
                .run(orm.getEntityManager());
    }

    @Test
    public void testNotNullConstraint() {
        expectedException.expect(PersistenceException.class);
        expectedException.expectCause(isA(PropertyValueException.class));
        expectedException.expectMessage("not-null property");

        IParticipant e1 = orm.getModelFactory().createParticipant();
        e1.setEmail(null);
        orm.em().getTransaction().begin();
        orm.em().persist(e1);
        orm.em().flush();
    }

    @Test
    public void testPersonEmailNotNullConstraintJdbc() throws SQLException {
        assertFalse(orm.getDatabaseGateway().isNullable(Constants.T_PARTICIPANT, Constants.M_PERSON_EMAIL));
    }

}
