package com.seer.teach.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.iot.module.entity.UserDevicesEntity;
import com.seer.teach.iot.module.mapper.UserDevicesMapper;
import com.seer.teach.iot.service.UserDevicesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户设备服务实现类，用于管理用户与设备之间的绑定关系及相关业务逻辑操作。
 * </p>
 *
 * @author Captain
 * @since 2025-05-08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDevicesServiceImpl extends ServiceImpl<UserDevicesMapper, UserDevicesEntity> implements UserDevicesService {

    /**
     * 根据设备 ID 获取关联的用户 ID。
     *
     * @param deviceId 设备 ID
     * @return Integer 用户 ID
     * @throws IllegalArgumentException 如果设备未绑定，抛出异常
     */
    @Override
    public Integer getUserIdByDeviceId(Integer deviceId) {
        UserDevicesEntity userDevice = getOne(new LambdaQueryWrapper<UserDevicesEntity>()
                .eq(UserDevicesEntity::getDeviceId, deviceId));
        AssertUtils.notNull(userDevice, ResultCodeEnum.EQUIPMENT_NOT_BIND);
        return userDevice.getUserId();
    }

    /**
     * 根据用户 ID 获取关联的设备 ID。
     *
     * @param userId 用户 ID
     * @return Integer 设备 ID
     * @throws IllegalArgumentException 如果设备未绑定，抛出异常
     */
    @Override
    public Integer getDeviceIdByUserId(Integer userId) {
        UserDevicesEntity userDevice = getOne(new LambdaQueryWrapper<UserDevicesEntity>()
                .eq(UserDevicesEntity::getUserId, userId));
        AssertUtils.notNull(userDevice, ResultCodeEnum.EQUIPMENT_NOT_BIND);
        return userDevice.getDeviceId();
    }

    @Override
    public boolean bindDevice(Integer userId, Integer deviceId) {
        UserDevicesEntity userDevicesEntity = new UserDevicesEntity();
        userDevicesEntity.setUserId(userId);
        userDevicesEntity.setDeviceId(deviceId);
        log.info("设备绑定成功 DeviceId：{} UserId:{}", deviceId, userId);
        return this.save(userDevicesEntity);
    }

}