package shop.alien.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import shop.alien.entity.second.SecondUserCreditRecord;
import shop.alien.mapper.second.SecondUserCreditRecordMapper;
import shop.alien.second.service.SecondUserCreditRecordService;

import java.util.Date;
import java.util.List;

/**
 * 二手平台用户积分记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondUserCreditRecordServiceImpl extends ServiceImpl<SecondUserCreditRecordMapper, SecondUserCreditRecord> implements SecondUserCreditRecordService {
    
    private final SecondUserCreditRecordMapper secondUserCreditRecordMapper;
    
    /**
     * 根据用户ID获取积分记录列表
     * @param userId 用户ID
     * @return 积分记录列表
     */
    @Override
    public List<SecondUserCreditRecord> getRecordsByUserId(Integer userId) {
        log.info("查询用户积分记录，userId={}", userId);
        LambdaQueryWrapper<SecondUserCreditRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondUserCreditRecord::getUserId, userId)
                .eq(SecondUserCreditRecord::getDeleteFlag, 0)
                .orderByDesc(SecondUserCreditRecord::getCreatedTime);
        return secondUserCreditRecordMapper.selectList(queryWrapper);
    }
    
    /**
     * 创建积分记录
     * @param record 积分记录信息
     * @return 是否创建成功
     */
    @Override
    public boolean createRecord(SecondUserCreditRecord record) {
        try {
            log.info("创建积分记录，userId={}, points={}", record.getUserId(), record.getPoints());
            record.setDeleteFlag(0);
            record.setCreatedTime(new Date());
            record.setUpdatedTime(new Date());
            int result = secondUserCreditRecordMapper.insert(record);
            return result > 0;
        } catch (Exception e) {
            log.error("创建积分记录失败，userId={}, points={}", record.getUserId(), record.getPoints(), e);
            return false;
        }
    }
}