package com.dora.service.impl;

import com.dora.entity.User;
import com.dora.mapper.UserMapper;
import com.dora.service.UserMembershipService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户会员服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserMembershipServiceImpl implements UserMembershipService {

    private final UserMapper userMapper;

    @Override
    @Transactional
    public void updateUserMembershipStatus() {
        try {
            log.info("开始执行用户会员状态更新任务");
            
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            
            // 批量更新过期会员状态
            int updatedCount = userMapper.updateExpiredMembership(now);
            
            log.info("用户会员状态更新任务执行完成，更新了 {} 个过期会员", updatedCount);
        } catch (Exception e) {
            log.error("用户会员状态更新任务执行失败", e);
        }
    }

    @Override
    @Transactional
    public void setDefaultVipForNewUser(Long userId) {
        try {
            // 获取用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                log.error("用户不存在，无法设置默认VIP身份 - userId: {}", userId);
                return;
            }

            // 设置VIP角色（角色2）和2天后的过期时间
            LocalDateTime vipExpiresAt = LocalDateTime.now().plusDays(2);
            
            // 更新用户角色和会员过期时间
            int result = userMapper.updateRoleAndMembership(userId, 2, vipExpiresAt);
            
            if (result > 0) {
                log.info("新用户默认VIP身份设置成功 - userId: {}, expiresAt: {}", userId, vipExpiresAt);
            } else {
                log.error("新用户默认VIP身份设置失败 - userId: {}", userId);
            }
        } catch (Exception e) {
            log.error("设置新用户默认VIP身份失败 - userId: {}", userId, e);
        }
    }
} 