package com.example.scaffold.service.impl;

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

import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现 - 演示 Spring 服务层
 * 
 * 学习要点：
 * 1. @Service - 标记为服务组件
 * 2. @Transactional - 声明式事务
 * 3. @RequiredArgsConstructor - Lombok 构造器注入
 * 4. @Slf4j - Lombok 日志
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final UserMapper userMapper;
    
    @Override
    public List<User> findAll() {
        log.info("📊 [UserService] 查询所有用户");
        return userMapper.findAll();
    }
    
    @Override
    public Optional<User> findById(Long id) {
        log.info("🔍 [UserService] 查询用户: id={}", id);
        // 演示 MyBatis 一级缓存 - 连续两次查询
        User user = userMapper.findById(id);
        User cached = userMapper.findById(id); // 第二次会命中缓存
        if (cached != null) {
            log.info("✅ [UserService] 一级缓存命中: id={}", id);
        }
        return Optional.ofNullable(user);
    }
    
    @Override
    @Transactional
    public User save(User user) {
        log.info("💾 [UserService] 保存用户: {}", user.getUsername());
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
        return user;
    }
    
    @Override
    @Transactional
    public void deleteById(Long id) {
        log.info("🗑️ [UserService] 删除用户: id={}", id);
        userMapper.deleteById(id);
    }
    
    @Override
    public List<User> searchByUsername(String username) {
        log.info("🔎 [UserService] 搜索用户: username={}", username);
        return userMapper.findByUsernameLike(username);
    }
    
    @Override
    public long count() {
        return userMapper.count();
    }
}