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

import com.bcxin.Infrastructures.components.JsonProvider;
import com.bcxin.Infrastructures.events.handlers.DomainEventHandlerAbstract;
import com.bcxin.tenant.domain.entities.EmployeeRecordEntity;
import com.bcxin.tenant.domain.enums.EmployeeEventType;
import com.bcxin.tenant.domain.enums.EventAction;
import com.bcxin.tenant.domain.events.EmployeeUpdatedEvent;
import com.bcxin.tenant.domain.repositories.EmployeeRecordRepository;
import com.bcxin.tenant.domain.services.TenantEventService;
import com.bcxin.tenant.domain.services.commands.CreateTenantEventCommand;
import com.bcxin.tenant.domain.snapshots.TenantEmployeeSnapshot;
import org.springframework.stereotype.Component;

@Component
public class EmployeeUpdatedEvent_Handler extends DomainEventHandlerAbstract<EmployeeUpdatedEvent> {
    private final TenantEventService tenantEventService;
    private final JsonProvider jsonProvider;
    private final EmployeeRecordRepository employeeRecordRepository;

    public EmployeeUpdatedEvent_Handler(TenantEventService tenantEventService, JsonProvider jsonProvider,
                                        EmployeeRecordRepository employeeRecordRepository) {
        this.tenantEventService = tenantEventService;
        this.jsonProvider = jsonProvider;
        this.employeeRecordRepository = employeeRecordRepository;
    }

    @Override
    protected void execute(EmployeeUpdatedEvent event) {
        TenantEmployeeSnapshot snapshot = TenantEmployeeSnapshot.create(
                event.getData().getId()
        );

        String json = this.jsonProvider.getJson(snapshot);
        this.tenantEventService.create(
                CreateTenantEventCommand.create(EventAction.EmployeeEdited, json,
                        event.getData().getTenantUser().getTelephone())
        );

        /**
         * 针对复职或者入职执行入离职记录的记录
         */
        if (event.getEventType() == EmployeeEventType.EntryJob || event.getEventType() == EmployeeEventType.LeaveJob) {
            EmployeeRecordEntity record =
                    EmployeeRecordEntity.create(event.getData());
            this.employeeRecordRepository.save(record);
        }
    }
}
