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

import cn.hutool.core.util.ObjectUtil;
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.openapi.entity.SnCodesEntity;
import com.seer.teach.openapi.mapper.SnCodesMapper;
import com.seer.teach.openapi.service.SnCodesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * SN授权表 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-10-31 13:31:24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SnCodesServiceImpl extends ServiceImpl<SnCodesMapper, SnCodesEntity> implements SnCodesService {

    private final static Integer TOKEN_EXPIRE = 7200;

    /**
     * API认证接口实现
     *
     * @param params 认证请求参数，包含SN码等信息
     * @return ApiAuthResp 认证响应结果，包含token信息
     */
    @Override
    public SnCodesEntity auth(String sn) {
        log.info("Auth :{}", sn);
        // 根据SN码查询设备信息
        SnCodesEntity snEntity = getOne(new LambdaQueryWrapper<SnCodesEntity>()
                .eq(SnCodesEntity::getSnCode, sn));
        AssertUtils.notNull(snEntity, ResultCodeEnum.API_SN_ERROR);
        AssertUtils.isTrue(snEntity.getStatus().equals(1), ResultCodeEnum.API_IS_DISABLE);
        // 检查SN码是否过期
        if (ObjectUtil.isNotNull(snEntity.getExpireTime())) {
            AssertUtils.isTrue(snEntity.getExpireTime().isAfter(LocalDateTime.now()), ResultCodeEnum.API_SN_EXPIRE);
        }
        return snEntity;
    }

}
