package com.xindazhou.vehicle.service.auth;

import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleAuthPageReqVO;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleAuthRespVO;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleAuthSaveReqVO;
import com.xindazhou.vehicle.convert.auth.VehicleAuthConvert;
import com.xindazhou.vehicle.dal.dataobject.auth.VehicleAuthDO;
import com.xindazhou.vehicle.dal.mysql.auth.VehicleAuthMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.xindazhou.vehicle.enums.ErrorCodeConstants.VEHICLE_AUTH_NOT_EXISTS;

/**
 * 车辆授权设置 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Validated
public class VehicleAuthServiceImpl implements VehicleAuthService {

    @Resource
    private VehicleAuthMapper authMapper;

    @Override
    public PageResult<VehicleAuthRespVO> getVehicleAuthPage(VehicleAuthPageReqVO pageReqVO) {
        PageResult<VehicleAuthDO> pageResult = authMapper.selectPage(pageReqVO);
        return VehicleAuthConvert.INSTANCE.convertPage(pageResult);
    }

    @Override
    public VehicleAuthRespVO getVehicleAuth(Long id) {
        VehicleAuthDO auth = authMapper.selectById(id);
        if (auth == null) {
            throw ServiceExceptionUtil.exception(VEHICLE_AUTH_NOT_EXISTS);
        }
        return VehicleAuthConvert.INSTANCE.convert(auth);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createVehicleAuth(VehicleAuthSaveReqVO createReqVO) {
        VehicleAuthDO auth = VehicleAuthConvert.INSTANCE.convert(createReqVO);
        authMapper.insert(auth);
        return auth.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVehicleAuth(VehicleAuthSaveReqVO updateReqVO) {
        validateVehicleAuthExists(updateReqVO.getId());
        VehicleAuthDO updateObj = VehicleAuthConvert.INSTANCE.convert(updateReqVO);
        authMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteVehicleAuth(Long id) {
        validateVehicleAuthExists(id);
        authMapper.deleteById(id);
    }

    private void validateVehicleAuthExists(Long id) {
        if (authMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(VEHICLE_AUTH_NOT_EXISTS);
        }
    }

}
