package dev.fyloz.trial.colorrecipesexplorer.service

import dev.fyloz.trial.colorrecipesexplorer.model.Company
import dev.fyloz.trial.colorrecipesexplorer.model.CompanySaveDto
import dev.fyloz.trial.colorrecipesexplorer.model.CompanyUpdateDto
import dev.fyloz.trial.colorrecipesexplorer.model.company
import dev.fyloz.trial.colorrecipesexplorer.repository.CompanyRepository
import dev.fyloz.trial.colorrecipesexplorer.service.model.RecipeJavaService
import org.springframework.stereotype.Service

interface CompanyService : ExternalNamedModelService<Company, CompanySaveDto, CompanyUpdateDto, CompanyRepository> {
    /** Checks if the given [company] is used by one or more recipes. */
    fun isLinkedToRecipes(company: Company): Boolean
}

@Service
class CompanyServiceImpl(companyRepository: CompanyRepository, val recipeService: RecipeJavaService) :
    AbstractExternalNamedModelService<Company, CompanySaveDto, CompanyUpdateDto, CompanyRepository>(companyRepository),
    CompanyService {
    override fun isLinkedToRecipes(company: Company): Boolean = recipeService.existsByCompany(company)

    override fun update(entity: CompanyUpdateDto): Company {
        // Lazy loaded to prevent checking the database when not necessary
        val persistedCompany by lazy { getById(entity.id) }

        return update(with(entity) {
            company(
                id = id,
                name = if (name != null && name.isNotBlank()) name else persistedCompany.name
            )
        })
    }
}
