package com.example.scaffold.learning.lifecycle;

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

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

@Component("iocPrototypeLifecycleBean")
@Scope("prototype")
public class PrototypeLifecycleBean implements LifecycleDemoBean {

    static {
        IocLifecycleTracker.record("iocPrototypeLifecycleBean", "prototype", "class-load", "JVM 初始化类（static block，仅第一次）");
    }

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

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

    @PostConstruct
    public void init() {
        IocLifecycleTracker.record("iocPrototypeLifecycleBean", "prototype", "post-construct", "原型 Bean 初始化完成");
    }

    @PreDestroy
    public void destroy() {
        IocLifecycleTracker.record("iocPrototypeLifecycleBean", "prototype", "pre-destroy", "注意：prototype Bean 默认不会由容器统一销毁");
    }

    @Override
    public Map<String, Object> inspect(String trigger) {
        int count = accessCount.incrementAndGet();
        IocLifecycleTracker.record("iocPrototypeLifecycleBean", "prototype", "method-call", "trigger=" + trigger + ", accessCount=" + count);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("beanName", "iocPrototypeLifecycleBean");
        result.put("scope", "prototype");
        result.put("instanceId", instanceId);
        result.put("identityHashCode", System.identityHashCode(this));
        result.put("accessCount", count);
        result.put("explanation", "原型 Bean 每次获取都会创建新实例，因此实例 ID / hashCode 会变化");
        return result;
    }
}
