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

import com.bcxin.tenant.open.domains.entities.UserPurseTransactionEntity;
import com.bcxin.tenant.open.domains.repositories.UserPurseRepository;
import com.bcxin.tenant.open.domains.services.UserPurseService;
import com.bcxin.tenant.open.domains.services.commands.CreateUserPurseTransactionCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.stream.Collectors;

@Service
public class UserPurseServiceImpl implements UserPurseService {

    private final UnitWork unitWork;
    private final UserPurseRepository userPurseRepository;

    public UserPurseServiceImpl(UnitWork unitWork, UserPurseRepository userPurseRepository) {
        this.unitWork = unitWork;
        this.userPurseRepository = userPurseRepository;
    }

    @Override
    public void dispatch(CreateUserPurseTransactionCommand.CreateUserPurseTransactionsCommand command) {

        Collection<UserPurseTransactionEntity>
                transactionEntities =
                command.getTransactions().stream().map(ii -> UserPurseTransactionEntity.create(
                        ii.getReferenceType(),
                        ii.getReferenceNumber(),
                        ii.getNote(),
                        ii.getPoints(),
                        ii.getTenantUserId()
                )).collect(Collectors.toList());

        this.unitWork.executeTran(() -> {
            this.userPurseRepository.addTransactions(transactionEntities);
        });
    }
}
