package com.example.demo.service;

import com.example.demo.exception.ResourceNotFoundException;
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
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()
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: id=" + id));
    }

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

    public User create(User user) {
        user.setId(idGenerator.getAndIncrement());
        users.add(user);
        return user;
    }

    public User update(Long id, User user) {
        findById(id);
        user.setId(id);
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId().equals(id)) {
                users.set(i, user);
                return user;
            }
        }
        throw new ResourceNotFoundException("用户不存在: id=" + id);
    }

    public void delete(Long id) {
        boolean removed = users.removeIf(u -> u.getId().equals(id));
        if (!removed) {
            throw new ResourceNotFoundException("用户不存在: id=" + id);
        }
    }
}
