package com.ffii.lioner.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
  
  // @Override
  // public void addCorsMappings(CorsRegistry registry) {
  //   registry.addMapping("/**")
  //       .allowedHeaders("*")
  //       .allowedOrigins(url)
  //       .exposedHeaders("filename")
  //       .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD");

  // }
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**") // Apply to all API endpoints
          .allowedHeaders("*")
          // **** CRITICAL FIX HERE ****
          .allowedOrigins(
            "http://localhost",       // If you test locally via Nginx at http://localhost
            "http://127.0.0.1",       // Sometimes browsers resolve localhost to 127.0.0.1
            "http://52.175.15.19",    // Your 2fi-uat frontend IP            
            "http://localhost:3000" // If you ever run React dev server directly
            // Add any other specific domains/IPs/ports where your frontend will be hosted
        )
        // You had .exposedHeaders("filename") - keep if you need to read custom response headers
        .exposedHeaders("filename")
        // You had .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD") - This is missing "OPTIONS"
        .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS") // **** IMPORTANT: Add OPTIONS ****
        // You had .allowedHeaders("*") duplicated - harmless, but the first one is enough
        // .allowedHeaders("*")
        .allowCredentials(true)
        .maxAge(3600); // Recommended: Caches preflight results for 1 hour
}

  @Bean
  public InternalResourceViewResolver defaultViewResolver() {
    return new InternalResourceViewResolver();
  }

}