<?php

namespace App\Exceptions;

use App\Traits\HttpResponses;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Throwable;

class Handler extends ExceptionHandler
{
    use HttpResponses;

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        //
    }

    /**
     * Render an exception into an HTTP response.
     */
    public function render($request, Throwable $e)
    {
        $status = $this->getStatusCode($e);
        $message = $this->getMessage($e);

        return $this->error([
            'message' => $message,
            'code' => $status,
            'data' => $this->getErrorData($e),
        ], $status);
    }

    /**
     * Get the proper HTTP status code for the exception.
     */
    private function getStatusCode(Throwable $e): int
    {
        if ($e instanceof HttpExceptionInterface) {
            return $e->getStatusCode();
        }

        if ($e instanceof ValidationException) {
            return 422;
        }

        if ($e instanceof AuthenticationException) {
            return 401;
        }

        if ($e instanceof AuthorizationException) {
            return 403;
        }

        if ($e instanceof ModelNotFoundException) {
            return 404;
        }

        // fallback
        $code = (int) $e->getCode();

        return ($code >= 100 && $code < 600) ? $code : 500;
    }

    /**
     * Get a safe message for the exception.
     */
    private function getMessage(Throwable $e): string
    {
        if (config('app.debug')) {
            return $e->getMessage() ?: 'Server Error';
        }

        // Hide internal errors in production
        if ($e instanceof ValidationException) {
            return 'Validation failed';
        }
        if ($e instanceof AuthenticationException) {
            return 'Unauthenticated';
        }
        if ($e instanceof AuthorizationException) {
            return 'Unauthorized';
        }
        if ($e instanceof ModelNotFoundException) {
            return 'Resource not found';
        }

        return 'Server Error';
    }

    /**
     * Get extra error data (useful for validation errors).
     */
    private function getErrorData(Throwable $e): mixed
    {
        if ($e instanceof ValidationException) {
            return $e->errors();
        }

        return config('app.debug') ? [
            'exception' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
        ] : null;
    }
}
