package dev.fyloz.trial.colorrecipesexplorer.repository

import dev.fyloz.trial.colorrecipesexplorer.model.Material
import dev.fyloz.trial.colorrecipesexplorer.model.material
import dev.fyloz.trial.colorrecipesexplorer.model.materialType
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class MaterialRepositoryTest @Autowired constructor(materialRepository: MaterialRepository, entityManager: TestEntityManager) :
        AbstractNamedJpaRepositoryTest<Material, MaterialRepository>(materialRepository, entityManager) {
    override fun entity(name: String): Material = material(name = name, materialType = null)

    @Test
    fun `existsByMaterialType() returns true when a material with the given material type exists`() {
        val materialType = materialType()
        val material = material(materialType = materialType)

        entityManager.persist(materialType)
        entityManager.persist(material)

        val found = repository.existsByMaterialType(materialType)

        assertTrue(found)
    }

    @Test
    fun `existsByMaterialType() returns false when no material with the given material type exists`() {
        val materialType = materialType()

        entityManager.persist(materialType)

        val found = repository.existsByMaterialType(materialType)

        assertFalse(found)
    }

    @Test
    fun `findAllByMaterialType() returns all materials with the given material type`() {
        val materialType = materialType(name = "material type", prefix = "MAT")
        val anotherMaterialType = materialType(name = "another material type", prefix = "ANO")
        val material = material(name = "material", materialType = materialType)
        val anotherMaterial = material(name = "another material", materialType = materialType)
        val yetAnotherMaterial = material(name = "yet another material", materialType = anotherMaterialType)

        entityManager.persist(materialType)
        entityManager.persist(anotherMaterialType)
        entityManager.persist(material)
        entityManager.persist(anotherMaterial)
        entityManager.persist(yetAnotherMaterial)

        val found = repository.findAllByMaterialType(materialType)

        assertTrue(found.contains(material))
        assertTrue(found.contains(anotherMaterial))
        assertFalse(found.contains(yetAnotherMaterial))
    }
}
