package com.qqchen.deploy.backend.framework.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext has not been initialized");
        }
        try {
            return (T) applicationContext.getBean(name);
        } catch (BeansException e) {
            log.error("Failed to get bean by name: {}", name, e);
            throw new IllegalStateException("Could not find bean: " + name, e);
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        if (applicationContext == null) {
            throw new IllegalStateException("ApplicationContext has not been initialized");
        }
        try {
            return applicationContext.getBean(clazz);
        } catch (BeansException e) {
            log.error("Failed to get bean by class: {}", clazz.getName(), e);
            throw new IllegalStateException("Could not find bean of type: " + clazz.getName(), e);
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}