package at.procon.eventhub.processing.api;

import at.procon.eventhub.tachographfilesession.service.DriverNotFoundInSessionException;
import at.procon.eventhub.tachographfilesession.service.TachographFileSessionNotFoundException;
import java.time.OffsetDateTime;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice(basePackageClasses = UnifiedRuntimeProcessingController.class)
public class UnifiedRuntimeProcessingExceptionHandler {

    @ExceptionHandler({
            TachographFileSessionNotFoundException.class,
            DriverNotFoundInSessionException.class
    })
    public ResponseEntity<Map<String, Object>> notFound(RuntimeException exception) {
        return error(HttpStatus.NOT_FOUND, exception);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> badRequest(RuntimeException exception) {
        return error(HttpStatus.BAD_REQUEST, exception);
    }

    private ResponseEntity<Map<String, Object>> error(HttpStatus status, RuntimeException exception) {
        return ResponseEntity.status(status).body(Map.of(
                "timestamp", OffsetDateTime.now().toString(),
                "status", status.value(),
                "error", status.getReasonPhrase(),
                "message", exception.getMessage()
        ));
    }
}
