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

import cn.hutool.crypto.digest.BCrypt;
import com.xunhong.erp.turbo.api.user.dto.cmd.AdminCreateCmd;
import com.xunhong.erp.turbo.api.user.dto.cmd.EmployeeCreateCmd;
import com.xunhong.erp.turbo.api.user.dto.cmd.UserAuthCreateCmd;
import com.xunhong.erp.turbo.api.user.dto.enums.AdminTypeEnum;
import com.xunhong.erp.turbo.api.user.dto.enums.SocialTypeEnum;
import com.xunhong.erp.turbo.api.user.dto.vo.EmployeeVO;
import com.xunhong.erp.turbo.user.app.assembler.EmployeeAssembler;
import com.xunhong.erp.turbo.user.domain.entity.Employee;
import com.xunhong.erp.turbo.user.domain.entity.UserAuth;
import com.xunhong.erp.turbo.user.domain.gateway.AdminGateway;
import com.xunhong.erp.turbo.user.domain.gateway.EmployeeGateway;
import com.xunhong.erp.turbo.user.domain.gateway.UserAuthGateway;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author shenyifei
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EmployeeCreateCmdExe {

	private final EmployeeAssembler employeeAssembler;
	private final EmployeeGateway employeeGateway;

	private final UserAuthGateway userAuthGateway;
	private final AdminGateway adminGateway;

	@Transactional
	public EmployeeVO execute(EmployeeCreateCmd employeeCreateCmd) {
		// 注册用户
		UserAuthCreateCmd userAuthCreateCmd = UserAuthCreateCmd.builder().socialType(SocialTypeEnum.ACCOUNT)
			.username(employeeCreateCmd.getUsername())
			.password(BCrypt.hashpw(employeeCreateCmd.getPassword()))
			.isAdmin(Boolean.TRUE)
			.build();
		UserAuth userAuth = userAuthGateway.register(userAuthCreateCmd);

		// 注册管理员
		AdminCreateCmd adminCreateCmd = AdminCreateCmd.builder()
			.userId(userAuth.getUserId())
			.name(employeeCreateCmd.getName())
			.type(AdminTypeEnum.SUB_ADMIN)
			.build();
		adminGateway.register(adminCreateCmd);

		// 创建员工
		employeeCreateCmd.setUserId(userAuth.getUserId());
		Employee employee = employeeGateway.save(employeeCreateCmd);

		return employeeAssembler.toEmployeeVO(employee);
	}
}
