package com.example.scaffold.learning.lifecycle;

import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class IocLifecycleTracker {

    private static final AtomicLong SEQ = new AtomicLong(0);
    private static final CopyOnWriteArrayList<Map<String, Object>> EVENTS = new CopyOnWriteArrayList<>();

    public static void record(String beanName, String scope, String phase, String detail) {
        Map<String, Object> event = new LinkedHashMap<>();
        event.put("seq", SEQ.incrementAndGet());
        event.put("time", Instant.now().toString());
        event.put("beanName", beanName);
        event.put("scope", scope);
        event.put("phase", phase);
        event.put("detail", detail);
        EVENTS.add(event);
    }

    public List<Map<String, Object>> snapshot() {
        return new ArrayList<>(EVENTS);
    }

    public void reset() {
        EVENTS.clear();
        SEQ.set(0);
        record("system", "n/a", "reset", "实验日志已重置");
    }
}
