package tutorial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

@org.springframework.context.annotation.Configuration
class Security {

  @org.springframework.context.annotation.Bean
  org.springframework.security.web.SecurityFilterChain filter(
    org.springframework.security.config.annotation.web.builders.HttpSecurity http
  ) throws Exception {
    return http
      .authorizeHttpRequests(a ->
        a
          .dispatcherTypeMatchers(jakarta.servlet.DispatcherType.ERROR)
          .permitAll()
          .requestMatchers("/public")
          .permitAll()
          .requestMatchers("/admin")
          .hasRole("ADMIN")
          .anyRequest()
          .authenticated()
      )
      .httpBasic(org.springframework.security.config.Customizer.withDefaults())
      .build();
  }

  @org.springframework.context.annotation.Bean
  org.springframework.security.core.userdetails.UserDetailsService users() {
    var encoder =
      org.springframework.security.crypto.factory.PasswordEncoderFactories.createDelegatingPasswordEncoder();
    return new org.springframework.security.provisioning.InMemoryUserDetailsManager(
      org.springframework.security.core.userdetails.User.withUsername("reader")
        .password(encoder.encode("local-reader"))
        .roles("USER")
        .build(),
      org.springframework.security.core.userdetails.User.withUsername("admin")
        .password(encoder.encode("local-admin"))
        .roles("ADMIN")
        .build()
    );
  }
}

@org.springframework.web.bind.annotation.RestController
class Api {

  @org.springframework.web.bind.annotation.GetMapping("/public")
  String publicPage() {
    return "public";
  }

  @org.springframework.web.bind.annotation.GetMapping("/admin")
  String admin() {
    return "admin";
  }

  @org.springframework.web.bind.annotation.PostMapping("/admin")
  String write() {
    return "changed";
  }
}
