package com.example.scaffold.learning.lifecycle;

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

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

@Component("iocLazySingletonLifecycleBean")
@Lazy
public class LazySingletonLifecycleBean implements LifecycleDemoBean {

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

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

    public LazySingletonLifecycleBean() {
        IocLifecycleTracker.record("iocLazySingletonLifecycleBean", "lazy-singleton", "constructor", "构造器执行，说明第一次真正获取才创建实例");
    }

    @PostConstruct
    public void init() {
        IocLifecycleTracker.record("iocLazySingletonLifecycleBean", "lazy-singleton", "post-construct", "Lazy 单例初始化完成，并被放入单例缓存");
    }

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

    @Override
    public Map<String, Object> inspect(String trigger) {
        int count = accessCount.incrementAndGet();
        IocLifecycleTracker.record("iocLazySingletonLifecycleBean", "lazy-singleton", "method-call", "trigger=" + trigger + ", accessCount=" + count);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("beanName", "iocLazySingletonLifecycleBean");
        result.put("scope", "lazy-singleton");
        result.put("instanceId", instanceId);
        result.put("identityHashCode", System.identityHashCode(this));
        result.put("accessCount", count);
        result.put("explanation", "Lazy 单例不会在容器启动时创建，而是在第一次 getBean 时才真正实例化");
        return result;
    }
}
