package com.yeejoin.amos.boot.module.jg.biz.reminder.core.event.adapter;

import com.yeejoin.amos.boot.module.jg.biz.edit.event.BaseBizDataChangeEvent;
import com.yeejoin.amos.boot.module.jg.biz.reminder.core.event.EquipCreateOrEditEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@RequiredArgsConstructor
@Slf4j
public class EditEventAdapter {

    private final ApplicationEventPublisher publisher;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void handleEventAsync(BaseBizDataChangeEvent event) {
        log.info("receive editEvent handleEventAAsync eventA={}", event);
        try {
            publisher.publishEvent(convertToEvent(event));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    private EquipCreateOrEditEvent convertToEvent(BaseBizDataChangeEvent eventA) {
        return new EquipCreateOrEditEvent(
                this,
                eventA.getBizRelationData().getBizType(),
                eventA.getBizRelationData().getProjectContraptionIds().isEmpty() ? eventA.getBizRelationData().getRecords() : eventA.getBizRelationData().getProjectContraptionIds(),
                eventA.getBizRelationData().getProjectContraptionIds().isEmpty() ? EquipCreateOrEditEvent.EquipType.equip : EquipCreateOrEditEvent.EquipType.project
        );
    }
}
