package com.bcxin.tenant.domain.events.handlers;

import cn.hutool.core.collection.CollUtil;
import com.bcxin.Infrastructures.UnitWork;
import com.bcxin.Infrastructures.events.handlers.DomainEventHandlerAbstract;
import com.bcxin.tenant.domain.entities.EmployeeEventEntity;
import com.bcxin.tenant.domain.enums.EmployeeEventType;
import com.bcxin.tenant.domain.events.EmployeeHiredDateChangeEvent;
import com.bcxin.tenant.domain.repositories.EmployeeEventRepository;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.ArrayList;

@Component
public class EmployeeHiredDateChangeEvent_Handler extends DomainEventHandlerAbstract<EmployeeHiredDateChangeEvent> {
    private final EmployeeEventRepository employeeEventRepository;
    private final UnitWork unitWork;

    public EmployeeHiredDateChangeEvent_Handler(EmployeeEventRepository employeeEventRepository,
                                                                  UnitWork unitWork) {
        this.employeeEventRepository = employeeEventRepository;
        this.unitWork = unitWork;
    }
    @Override
    protected void execute(EmployeeHiredDateChangeEvent event) {
        ArrayList<EmployeeEventEntity> entities = employeeEventRepository.getLatelyByIdAndType(event.getData().getId(), EmployeeEventType.EntryJob);
        if (CollUtil.isNotEmpty(entities)){
            EmployeeEventEntity entity = entities.get(0);
            Timestamp eventTime = event.getEventTime();
            entity.changeEventTime(eventTime);
            this.unitWork.executeTran(()->{
                this.employeeEventRepository.save(entity);
            });
        }
    }
}
