<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class VerifyServer
{
    public function handle($request, Closure $next)
    {
        $serverId = $request->header('X-SERVER-ID');
        $apiKey   = $request->header('X-API-KEY');

        if (!$serverId || !$apiKey) {
            return response()->json(['error' => 'missing_headers'], 403);
        }

        // Load server row
        $server = DB::table('server_settings')->where('server_id', $serverId)->first();

        if (!$server) {
            return response()->json(['error' => 'server_not_found'], 404);
        }

        // Compare the plugin key with DB key
        if ($server->websender_password !== $apiKey) {
            return response()->json(['error' => 'invalid_key'], 403);
        }

        // Attach server to request for controller usage
        $request->merge(['server' => $server]);

        return $next($request);
    }
}
