package com.bcxin.tenant.open.domains.services.impls;

import com.bcxin.tenant.open.domains.entities.TenantWarnContentEntity;
import com.bcxin.tenant.open.domains.repositories.TenantWarnContentRepository;
import com.bcxin.tenant.open.domains.services.TenantWarnContentService;
import com.bcxin.tenant.open.domains.services.commands.CreateTenantWarnContentCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class TenantWarnContentServiceImpl implements TenantWarnContentService {

    private static final Logger logger = LoggerFactory.getLogger(TenantWarnContentServiceImpl.class);

    private final UnitWork unitWork;
    private final TenantWarnContentRepository tenantWarnContentRepository;

    public TenantWarnContentServiceImpl(UnitWork unitWork, TenantWarnContentRepository tenantWarnContentRepository) {
        this.unitWork = unitWork;
        this.tenantWarnContentRepository = tenantWarnContentRepository;
    }

    @Override
    public void dispatch(CreateTenantWarnContentCommand command) {
        String tranId = this.unitWork.beginTransaction();
        try {
            this.tenantWarnContentRepository.insert(TenantWarnContentEntity.create(
                    command.getContentType(),
                    command.getReferenceNumber(),
                    command.getContent()
            ));
            this.unitWork.commit(tranId);
        } catch (Exception ex) {
            this.unitWork.rollback(tranId);

            logger.error("Failed to handler CreateTenantWarnContentCommand with error ", ex);
        }
    }
}
