package com.example.scaffold.learning.lifecycle;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Component("iocSingletonLifecycleBean")
public class SingletonLifecycleBean implements LifecycleDemoBean {

    static {
        IocLifecycleTracker.record("iocSingletonLifecycleBean", "singleton", "class-load", "JVM 初始化类（static block）");
    }

    private final String instanceId = UUID.randomUUID().toString().substring(0, 8);
    private final AtomicInteger accessCount = new AtomicInteger(0);

    public SingletonLifecycleBean() {
        IocLifecycleTracker.record("iocSingletonLifecycleBean", "singleton", "constructor", "构造器执行，实例ID=" + instanceId);
    }

    @PostConstruct
    public void init() {
        IocLifecycleTracker.record("iocSingletonLifecycleBean", "singleton", "post-construct", "Bean 初始化完成，已进入单例生命周期");
    }

    @PreDestroy
    public void destroy() {
        IocLifecycleTracker.record("iocSingletonLifecycleBean", "singleton", "pre-destroy", "容器关闭时销毁单例 Bean");
    }

    @Override
    public Map<String, Object> inspect(String trigger) {
        int count = accessCount.incrementAndGet();
        IocLifecycleTracker.record("iocSingletonLifecycleBean", "singleton", "method-call", "trigger=" + trigger + ", accessCount=" + count);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("beanName", "iocSingletonLifecycleBean");
        result.put("scope", "singleton");
        result.put("instanceId", instanceId);
        result.put("identityHashCode", System.identityHashCode(this));
        result.put("accessCount", count);
        result.put("explanation", "单例 Bean 在容器中通常只创建一次，后续每次获取都是同一个实例");
        return result;
    }
}
