package org.nstart.dep265.requestservice.controller

import org.nstart.dep265.requestservice.dto.ErrorResponseDto
import org.nstart.dep265.requestservice.service.InvalidCellsQueryException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

@RestControllerAdvice(assignableTypes = [CellsController::class])
class CellsApiExceptionHandler {
    @ExceptionHandler(InvalidCellsQueryException::class)
    fun handleInvalidCellsQuery(exception: InvalidCellsQueryException): ResponseEntity<ErrorResponseDto> {
        return validationError(exception.message ?: "Некорректные query parameters")
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException::class)
    fun handleTypeMismatch(exception: MethodArgumentTypeMismatchException): ResponseEntity<ErrorResponseDto> {
        return validationError("Некорректное значение query parameter: ${exception.name}")
    }

    private fun validationError(message: String): ResponseEntity<ErrorResponseDto> {
        return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .body(
                ErrorResponseDto(
                    code = "VALIDATION_ERROR",
                    message = message,
                ),
            )
    }
}
