package com.leisingha.ledger.config;

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

/**
 * Lets a browser page on another origin call this API.
 *
 * <p>Without this, the project page can fetch nothing: the browser sends a
 * preflight OPTIONS first and refuses the real request unless the server names
 * the calling origin. Note {@code Idempotency-Key} in the allowed headers — it is
 * a custom header, so it does not survive preflight unless it is listed, and
 * every POST here carries one.
 *
 * <p>Origins are configuration, never a wildcard. {@code *} would let any page on
 * the internet drive this API from a visitor's browser, which for something that
 * moves money is not a trade worth making. The default covers local development
 * only; a deployed page adds its own origin.
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    private final List<String> allowedOrigins;

    public CorsConfig(@Value("${ledger.cors.allowed-origins:}") List<String> allowedOrigins) {
        this.allowedOrigins = allowedOrigins.stream().filter(o -> !o.isBlank()).toList();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if (allowedOrigins.isEmpty()) {
            return;
        }

        registry.addMapping("/api/**")
            .allowedOrigins(allowedOrigins.toArray(String[]::new))
            .allowedMethods("GET", "POST")
            .allowedHeaders("Content-Type", "Idempotency-Key")
            .maxAge(3600);
    }
}
