package app.mealsmadeeasy.api.util;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionHandlers {

    public record NoSuchEntityWithIdExceptionView<T>(String entityName, T id, String message) {}

    @ExceptionHandler(NoSuchEntityWithIdException.class)
    public ResponseEntity<NoSuchEntityWithIdExceptionView<?>> handleNoSuchEntityWithIdException(
            NoSuchEntityWithIdException e
    ) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(new NoSuchEntityWithIdExceptionView<>(
                        e.getEntityType().getSimpleName(),
                        e.getId(),
                        String.format("No such entity %s with id %s", e.getEntityType().getSimpleName(), e.getId())
                ));
    }

    public record NoSuchEntityWithUsernameAndSlugExceptionView(
            String entityName,
            String username,
            String slug,
            String message
    ) {}

    @ExceptionHandler(NoSuchEntityWithUsernameAndSlugException.class)
    public ResponseEntity<NoSuchEntityWithUsernameAndSlugExceptionView> handleNoSuchEntityWithUsernameAndSlugException(
            NoSuchEntityWithUsernameAndSlugException e
    ) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new NoSuchEntityWithUsernameAndSlugExceptionView(
                e.getEntityType().getSimpleName(),
                e.getUsername(),
                e.getSlug(),
                String.format(
                        "No such entity %s for username %s and slug %s",
                        e.getEntityType().getSimpleName(),
                        e.getUsername(),
                        e.getSlug()
                )
        ));
    }

    public record NoSuchEntityWithUsernameAndFilenameExceptionView(
            String entityName,
            String username,
            String filename,
            String message
    ) {}

    @ExceptionHandler(NoSuchEntityWithUsernameAndFilenameException.class)
    public ResponseEntity<NoSuchEntityWithUsernameAndFilenameExceptionView> handleNoSuchEntityWithUsernameAndFilename(
            NoSuchEntityWithUsernameAndFilenameException e
    ) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new NoSuchEntityWithUsernameAndFilenameExceptionView(
                e.getEntityType().getSimpleName(),
                e.getUsername(),
                e.getFilename(),
                String.format(
                        "No such entity %s for username %s and filename %s",
                        e.getEntityType().getSimpleName(),
                        e.getUsername(),
                        e.getFilename()
                )
        ));
    }

}
