<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

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

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (\Illuminate\Validation\ValidationException $e, $request) {
            if ($request->is('api/*')) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $e->errors()
                ], 422);
            }
        });

        $this->renderable(function (\Throwable $e, $request) {
            if ($request->is('api/*')) {
                return $this->handleApiExceptions($e);
            }
        });
    }

    private function handleApiExceptions(\Throwable $e)
    {
        $statusCode = 500;
        $response = [
            'status' => 'error',
            'message' => 'An internal error occurred',
            'code' => 'INTERNAL_SERVER_ERROR'
        ];

        if ($e instanceof \Illuminate\Validation\ValidationException) {
            $statusCode = 422;
            $response['message'] = 'Validation failed';
            $response['code'] = 'VALIDATION_ERROR';
            $response['errors'] = $e->errors();
        } elseif ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
            $statusCode = 404;
            $response['message'] = 'Resource not found';
            $response['code'] = 'NOT_FOUND';
        } elseif ($e instanceof \Illuminate\Auth\AuthenticationException) {
            $statusCode = 401;
            $response['message'] = 'Unauthenticated';
            $response['code'] = 'AUTHENTICATION_ERROR';
        } elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
            $statusCode = 404;
            $response['message'] = 'Endpoint not found';
            $response['code'] = 'ROUTE_NOT_FOUND';
        } elseif ($e instanceof \Illuminate\Auth\Access\AuthorizationException) {
            $statusCode = 403;
            $response['message'] = 'Unauthorized access';
            $response['code'] = 'AUTHORIZATION_ERROR';
        } elseif ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
            $statusCode = $e->getStatusCode();
            $response['message'] = $e->getMessage() ?: 'Request failed';
            $response['code'] = 'HTTP_ERROR';
        } else {
            // Unexpected errors
            if (config('app.debug')) {
                $response['message'] = $e->getMessage();
                $response['debug'] = [
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'trace' => $e->getTraceAsString()
                ];
            }
        }

        return response()->json($response, $statusCode);
    }
}
