package com.atlassian.stash.internal.backup;

import com.google.common.collect.Iterables;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matchers;
import org.hamcrest.number.OrderingComparison;
import org.junit.Test;

import static com.atlassian.stash.internal.backup.DatabaseTable.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.*;

public class DatabaseTableTest {

    @Test
    public void testGetTableNames() {
        assertEquals("getTableNames() with no attributes should return all tables", DatabaseTable.values().length,
                Iterables.size(DatabaseTable.getTableNames()));

        for (String tableName : DatabaseTable.getTableNames(DatabaseTableAttribute.CROWD)) {
            assertThat("Asked for CROWD tables, but one doesn't start with 'cwd_'!", tableName, Matchers.startsWith("cwd_"));
        }
    }

    @Test
    public void sanityTestOrderingSatisfiesForeignKeyConstraints() {
        // will fail if someone, say, alphabetizes the DatabaseTable enum
        assertThat(String.format("%s table should always precede %s table to appease foreign key constraints on restore!",
                STA_PERMISSION_TYPE.getTableName(), STA_GLOBAL_PERMISSION.getTableName()),
            STA_PERMISSION_TYPE.ordinal(), OrderingComparison.lessThan(STA_GLOBAL_PERMISSION.ordinal()));
    }

    @Test
    public void testIsKnownTable() {
        assertTrue(isKnownTable(HIBERNATE_UNIQUE_KEY.getTableName()));
        assertFalse(isKnownTable("bogus"));
    }

    @Test
    public void testTableNamesAreLowerCase() throws Exception {
        for (DatabaseTable table : DatabaseTable.values()) {
            assertEquals(table.getTableName().toLowerCase(), table.getTableName());
        }
    }

    @Test
    public void testOrderingColumnIsNullOrNotBlank() throws Exception {
        for (DatabaseTable table : DatabaseTable.values()) {
            String orderingColumn = table.getOrderingColumn();
            assertTrue(orderingColumn == null || StringUtils.isNotBlank(orderingColumn));
        }
    }
}
