<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Server;

class ServerApiKeyAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $apiKey = $request->query('api_key') ?? $request->header('X-API-Key');
        
        if (!$apiKey) {
            return response()->json([
                'success' => false,
                'error' => 'API key is required'
            ], 400);
        }

        $server = Server::where('api_key', $apiKey)
            ->where('is_active', true)
            ->first();

        if (!$server) {
            return response()->json([
                'success' => false,
                'error' => 'Invalid API key or server not active'
            ], 401);
        }

        // Add server to request for controller use
        $request->attributes->add(['server' => $server]);

        return $next($request);
    }
}