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

import com.njcn.rdms.framework.security.core.util.SecurityFrameworkUtils;
import com.njcn.rdms.module.project.dal.dataobject.personal.PersonalItemDO;
import com.njcn.rdms.module.project.dal.mysql.project.execution.ExecutionAssigneeMapper;
import com.njcn.rdms.module.project.enums.ErrorCodeConstants;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;

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

@Service
public class PersonalItemAccessServiceImpl implements PersonalItemAccessService {

    @Resource
    private ExecutionAssigneeMapper executionAssigneeMapper;

    @Override
    public void checkCanWrite(PersonalItemDO item) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId == null || item == null || !Objects.equals(loginUserId, item.getOwnerId())) {
            throw exception(ErrorCodeConstants.PERSONAL_ITEM_WRITE_FORBIDDEN);
        }
    }

    @Override
    public void validateOwnerInExecution(Long executionId, Long ownerId) {
        if (executionId == null || ownerId == null
                || executionAssigneeMapper.selectActiveByExecutionIdAndUserId(executionId, ownerId) == null) {
            throw exception(ErrorCodeConstants.PERSONAL_ITEM_OWNER_NOT_IN_EXECUTION);
        }
    }
}
