package com.atlassian.stash.internal.setting;

import com.atlassian.bitbucket.annotation.Dao;
import com.atlassian.bitbucket.annotation.DataSet;
import com.atlassian.stash.internal.AbstractDaoTest;
import com.atlassian.stash.internal.DataSets;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

@DataSet(DataSets.SHARED_LOBS)
public class HibernateSharedLobDaoTest extends AbstractDaoTest {

    @Dao
    private HibernateSharedLobDao dao;

    @Test
    public void testCreate() {
        InternalSharedLob lob = new InternalSharedLob.Builder().data("{\"key\"=\"PROJECT\"}").build();
        InternalSharedLob created = dao.create(lob);
        assertNotNull(created.getId());

        flush();
        evict(created, created.getId());

        assertEquals(lob.getId(), created.getId());
        assertEquals(lob.getData(), dao.getById(created.getId()).getData());
    }

    @Test
    public void testDelete() {
        InternalSharedLob lob = dao.getById(2L);
        dao.delete(lob);

        flush();
        clear();

        assertNull(dao.getById(2L));
    }

    @Test
    public void testDeleteById() {
        dao.deleteById(1L);

        flush();
        clear();

        assertNull(dao.getById(1L));
    }

    @Test
    public void testGetById() {
        InternalSharedLob lob = dao.getById(1L);
        assertNotNull(lob);
        assertEquals("{}", lob.getData());
    }

    @Test
    public void testGetByIds() {
        List<InternalSharedLob> lobs = dao.getByIds(Arrays.asList(1L, 2L));
        assertNotNull(lobs);
        assertEquals(2, lobs.size());
        assertEquals("{}", lobs.get(0).getData());
        assertEquals("{\"key\"=\"value\"}", lobs.get(1).getData());
    }

    @Test
    public void testUpdate() {
        InternalSharedLob initial = dao.getById(2L);
        InternalSharedLob modified = new InternalSharedLob.Builder(initial)
                .data("updated")
                .build();
        dao.update(modified);

        flush();
        evict(modified, modified.getId());

        InternalSharedLob updated = dao.getById(2L);
        assertEquals("updated", updated.getData());
    }
}
