package com.example.dateplanner.configurations.filters;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;

@Slf4j
public class ErrorHandlingFilter implements WebFilter {
    @Override
    public @NotNull Mono<Void> filter(@NotNull ServerWebExchange exchange, WebFilterChain chain) {
        //log.info("error handler!");
        return chain.filter(exchange)
                .onErrorResume(error -> handleError(exchange, error))
                .then(Mono.defer(() -> handleNotFound(exchange)));
    }

    private Mono<Void> handleError(ServerWebExchange exchange, Throwable error) {
        HttpStatusCode status = determineStatusCode(error);
        return prepareRedirect(exchange, status);
    }

    private Mono<Void> handleNotFound(ServerWebExchange exchange) {
        if (exchange.getResponse().getStatusCode() == null) {
            return prepareRedirect(exchange, HttpStatus.NOT_FOUND);
        }
        return Mono.empty();
    }

    private Mono<Void> prepareRedirect(ServerWebExchange exchange, HttpStatusCode status) {
        exchange.getResponse().setStatusCode(HttpStatus.FOUND); // 302 Redirect
        String redirectUrl = "/error?status=" + status.value();
        exchange.getResponse().getHeaders().setLocation(URI.create(redirectUrl));
        return exchange.getResponse().setComplete();
    }

    private HttpStatusCode determineStatusCode(Throwable error) {
        if (error instanceof ResponseStatusException) {
            return ((ResponseStatusException) error).getStatusCode();
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}
