package com.njcn.rdms.module.project.service.product;

import com.njcn.rdms.module.project.constant.ProductObjectConstants;
import com.njcn.rdms.module.project.controller.admin.product.vo.setting.ProductSettingActionRespVO;
import com.njcn.rdms.module.project.controller.admin.product.vo.setting.ProductSettingLifecycleRespVO;
import com.njcn.rdms.module.project.dal.dataobject.status.ObjectStatusModelDO;
import com.njcn.rdms.module.project.dal.dataobject.status.ObjectStatusTransitionDO;
import com.njcn.rdms.module.project.dal.mysql.status.ObjectStatusModelMapper;
import com.njcn.rdms.module.project.dal.mysql.status.ObjectStatusTransitionMapper;
import com.njcn.rdms.module.project.enums.ErrorCodeConstants;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

import static com.njcn.rdms.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
public class ProductStatusViewService {

    @Resource
    private ObjectStatusModelMapper objectStatusModelMapper;
    @Resource
    private ObjectStatusTransitionMapper objectStatusTransitionMapper;

    public ProductSettingLifecycleRespVO getLifecycle(String statusCode, String lastStatusReason) {
        ObjectStatusModelDO statusModel = objectStatusModelMapper
                .selectByObjectTypeAndStatusCodeEnabled(ProductObjectConstants.OBJECT_TYPE, statusCode);
        if (statusModel == null) {
            throw exception(ErrorCodeConstants.PRODUCT_STATUS_MODEL_NOT_EXISTS_OR_DISABLED);
        }

        ProductSettingLifecycleRespVO lifecycle = new ProductSettingLifecycleRespVO();
        lifecycle.setStatusCode(statusModel.getStatusCode());
        lifecycle.setStatusName(statusModel.getStatusName());
        lifecycle.setTerminal(statusModel.getTerminalFlag());
        lifecycle.setAllowEdit(statusModel.getAllowEdit());
        lifecycle.setLastStatusReason(lastStatusReason);
        lifecycle.setAvailableActions(buildAvailableActions(statusCode));
        return lifecycle;
    }

    private List<ProductSettingActionRespVO> buildAvailableActions(String statusCode) {
        List<ObjectStatusTransitionDO> transitions = objectStatusTransitionMapper
                .selectListByObjectTypeAndFromStatus(ProductObjectConstants.OBJECT_TYPE, statusCode);
        if (transitions == null || transitions.isEmpty()) {
            return Collections.emptyList();
        }
        return transitions.stream().map(transition -> {
            ProductSettingActionRespVO action = new ProductSettingActionRespVO();
            action.setActionCode(transition.getActionCode());
            action.setActionName(transition.getActionName());
            action.setNeedReason(transition.getNeedReason());
            return action;
        }).toList();
    }

}
