package com.example.demo.service;

import com.example.demo.model.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 用户服务 - 业务逻辑层
 * 
 * 学习点：
 * - @Service: 标记为服务层组件，自动注册为 Bean
 * - 依赖注入：Controller 通过 @Autowired 注入此服务
 * - 分层架构：Controller -> Service -> Repository
 */
@Service
public class UserService {

    // 内存存储（演示用，实际项目用数据库）
    private final List<User> users = new ArrayList<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    public UserService() {
        // 初始化一些测试数据
        users.add(new User(idGenerator.getAndIncrement(), "张三", "zhangsan@example.com", 25));
        users.add(new User(idGenerator.getAndIncrement(), "李四", "lisi@example.com", 30));
        users.add(new User(idGenerator.getAndIncrement(), "王五", "wangwu@example.com", 28));
    }

    public List<User> findAll() {
        return new ArrayList<>(users);
    }

    public User findById(Long id) {
        return users.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    public List<User> findByName(String name) {
        return users.stream()
                .filter(u -> u.getName().contains(name))
                .collect(Collectors.toList());
    }

    public User save(User user) {
        if (user.getId() == null) {
            user.setId(idGenerator.getAndIncrement());
            users.add(user);
        } else {
            // 更新
            for (int i = 0; i < users.size(); i++) {
                if (users.get(i).getId().equals(user.getId())) {
                    users.set(i, user);
                    break;
                }
            }
        }
        return user;
    }

    public void delete(Long id) {
        users.removeIf(u -> u.getId().equals(id));
    }
}