package demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.util.*;

@Component
class Report implements ApplicationRunner {
    private final ApplicationContext ctx;
    Report(ApplicationContext ctx) { this.ctx = ctx; }

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("REPORT meta-annotations of @SpringBootApplication:");
        for (Annotation a : SpringBootApplication.class.getAnnotations())
            if (a.annotationType().getName().startsWith("org.springframework"))
                System.out.println("REPORT   " + a.annotationType().getSimpleName());
        System.out.println("REPORT meta-annotations of @RestController:");
        for (Annotation a : RestController.class.getAnnotations())
            if (a.annotationType().getName().startsWith("org.springframework"))
                System.out.println("REPORT   " + a.annotationType().getSimpleName());
        for (Class<? extends Annotation> t : List.of(org.springframework.stereotype.Service.class,
                org.springframework.stereotype.Repository.class, org.springframework.web.bind.annotation.RestController.class)) {
            System.out.println("REPORT @" + t.getSimpleName() + " is a @Component: "
                    + AnnotatedElementUtils.isAnnotated(t, org.springframework.stereotype.Component.class));
        }
        String[] mine = Arrays.stream(ctx.getBeanDefinitionNames())
                .filter(n -> ctx.getType(n) != null && ctx.getType(n).getName().startsWith("demo."))
                .sorted().toArray(String[]::new);
        System.out.println("REPORT beans from package demo:");
        for (String n : mine) System.out.println("REPORT   " + n + " -> " + ctx.getType(n).getSimpleName());
        System.out.println("REPORT total beans in context: " + ctx.getBeanDefinitionCount());
        System.out.println("REPORT DevOnly (@Profile(\"dev\")) present: " + ctx.containsBean("devOnly"));
    }
}
