package at.procon.eventhub.tachographfilesession.api;

import at.procon.eventhub.tachographfilesession.service.DriverNotFoundInSessionException;
import at.procon.eventhub.tachographfilesession.service.LegalRequirementsUploadException;
import at.procon.eventhub.tachographfilesession.service.LegalRequirementsXmlDownloadException;
import at.procon.eventhub.tachographfilesession.service.TachographFileSessionNotFoundException;
import at.procon.eventhub.tachographfilesession.service.TachographXmlValidationException;
import at.procon.eventhub.tachographfilesession.service.UnsupportedTachographFileTypeException;
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 = TachographFileSessionController.class)
public class TachographFileSessionExceptionHandler {

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

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

    @ExceptionHandler({
            LegalRequirementsUploadException.class,
            LegalRequirementsXmlDownloadException.class
    })
    public ResponseEntity<Map<String, Object>> badGateway(RuntimeException exception) {
        return error(HttpStatus.BAD_GATEWAY, 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()
        ));
    }
}
