package com.hclsoftware.sso.kerberos.v2.exceptions.handlers;

import com.hclsoftware.sso.kerberos.constants.CustomResponseStatus;
import com.hclsoftware.sso.kerberos.v2.exceptions.LoginDataNotFoundException;
import com.hclsoftware.sso.kerberos.v2.response.GenericResponse;
import org.ietf.jgss.GSSException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { LoginDataNotFoundException.class })
    public ResponseEntity<GenericResponse<String>> handleLoginDataNotFoundException(
            Exception ex, WebRequest request) {
        return new ResponseEntity<>(GenericResponse
                .error(CustomResponseStatus.LOGIN_AGAIN, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED, "Please login again."),
                new HttpHeaders(),
                HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
    }

    @ExceptionHandler(value = { UsernameNotFoundException.class })
    public ResponseEntity<GenericResponse<Throwable>> handleUsernameNotFoundException(
            Exception ex, WebRequest request) {
        return new ResponseEntity<>(GenericResponse
                .error(CustomResponseStatus.LOGIN_AGAIN, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED, ex.getCause()),
                new HttpHeaders(),
                HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
    }

    @ExceptionHandler(value = { Exception.class })
    public ResponseEntity<GenericResponse<String>> handleAllException(
            Exception ex, WebRequest request) {
        return new ResponseEntity<>(GenericResponse
                .error(CustomResponseStatus.ERROR, HttpStatus.INTERNAL_SERVER_ERROR),
                new HttpHeaders(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
