<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class HandleApiErrors
{
    public function handle(Request $request, Closure $next)
    {
        try {
            $response = $next($request);
            
            // Log server errors
            if ($response->status() >= 500) {
                Log::error('API Server Error', [
                    'url' => $request->fullUrl(),
                    'method' => $request->method(),
                    'status' => $response->status(),
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                    'request_time' => microtime(true) - LARAVEL_START,
                ]);
            }
            
            // Log 4xx errors (client errors)
            if ($response->status() >= 400 && $response->status() < 500) {
                Log::warning('API Client Error', [
                    'url' => $request->fullUrl(),
                    'method' => $request->method(),
                    'status' => $response->status(),
                    'ip' => $request->ip(),
                    'parameters' => $request->except(['password', 'api_key', 'token']),
                ]);
            }
            
            return $response;
            
        } catch (\Throwable $e) {
            Log::critical('Unhandled API Exception', [
                'message' => $e->getMessage(),
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'url' => $request->fullUrl(),
                'method' => $request->method(),
                'ip' => $request->ip(),
                'trace' => $e->getTraceAsString(),
            ]);
            
            return response()->json([
                'success' => false,
                'message' => 'Internal server error',
                'error_code' => 'INTERNAL_ERROR'
            ], 500);
        }
    }
}