package com.xunhong.erp.turbo.rbac.app.executor.cmd;

import com.xunhong.erp.turbo.api.rbac.dto.cmd.UserRoleUpdateCmd;
import com.xunhong.erp.turbo.api.rbac.dto.qry.RoleListQry;
import com.xunhong.erp.turbo.api.rbac.dto.vo.UserRoleVO;
import com.xunhong.erp.turbo.rbac.app.assembler.UserRoleAssembler;
import com.xunhong.erp.turbo.rbac.domain.entity.Role;
import com.xunhong.erp.turbo.rbac.domain.entity.UserRole;
import com.xunhong.erp.turbo.rbac.domain.gateway.RoleGateway;
import com.xunhong.erp.turbo.rbac.domain.gateway.UserRoleGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class UserRoleUpdateCmdExe {

	private final UserRoleGateway userRoleGateway;
	private final UserRoleAssembler userRoleAssembler;

	private final RoleGateway roleGateway;

	public List<UserRoleVO> execute(UserRoleUpdateCmd userRoleUpdateCmd) {
		RoleListQry roleListQry = new RoleListQry();
		roleListQry.setRoleIdList(userRoleUpdateCmd.getRoleIdList());
		List<Role> roleList = roleGateway.list(roleListQry);

		if (roleList.isEmpty()) {
			return new ArrayList<>();
		}

		userRoleUpdateCmd.setRoleIdList(roleList.stream().map(Role::getRoleId).collect(Collectors.toList()));
		List<UserRole> userRoleList = userRoleGateway.update(userRoleUpdateCmd);
		return userRoleList.stream().map(userRoleAssembler::toUserRoleVO).collect(Collectors.toList());
	}
}
