package com.honey.honey.config;

import org.springframework.beans.factory.annotation.Value;
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.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Configuration
public class CorsConfig {

    @Value("${FRONTEND_URL:}")
    private String frontendUrl;

    private static final List<String> ADDITIONAL_ORIGINS = Arrays.asList(
            "https://honey-test-fe-production.up.railway.app",
            "https://web.telegram.org",
            "https://webk.telegram.org",
            "https://t.me"
    );

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                List<String> origins = Stream.concat(
                        Arrays.stream(frontendUrl != null && !frontendUrl.isBlank()
                                ? frontendUrl.split("\\s*,\\s*")
                                : new String[]{}),
                        ADDITIONAL_ORIGINS.stream()
                ).filter(s -> s != null && !s.isBlank()).distinct().collect(Collectors.toList());

                if (origins.isEmpty()) {
                    origins = ADDITIONAL_ORIGINS;
                }

                registry.addMapping("/**")
                        .allowedOrigins(origins.toArray(new String[0]))
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}

