package at.procon.dip.domain.tenant.service;

import at.procon.dip.domain.tenant.entity.DocumentTenant;
import at.procon.dip.domain.tenant.repository.DocumentTenantRepository;
import at.procon.dip.domain.tenant.service.command.CreateTenantCommand;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
public class DocumentTenantService {

    private final DocumentTenantRepository tenantRepository;

    public DocumentTenant createOrUpdate(CreateTenantCommand command) {
        DocumentTenant tenant = tenantRepository.findByTenantKey(command.tenantKey())
                .orElseGet(DocumentTenant::new);
        tenant.setTenantKey(command.tenantKey());
        tenant.setDisplayName(command.displayName());
        tenant.setDescription(command.description());
        tenant.setActive(command.active());
        return tenantRepository.save(tenant);
    }

    @Transactional(readOnly = true)
    public DocumentTenant getRequiredById(UUID id) {
        return tenantRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Unknown tenant id: " + id));
    }

    @Transactional(readOnly = true)
    public DocumentTenant getRequiredByTenantKey(String tenantKey) {
        return tenantRepository.findByTenantKey(tenantKey)
                .orElseThrow(() -> new IllegalArgumentException("Unknown tenant key: " + tenantKey));
    }

    @Transactional(readOnly = true)
    public List<DocumentTenant> findAll() {
        return tenantRepository.findAll();
    }
}
