<?php

namespace App\Http\Middleware;

use App\Models\Terminal;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class IdentifyTerminal
{
    public function handle(Request $request, Closure $next): Response
    {
        $macHeader = $request->header('X-Terminal-MAC');

        if (!$macHeader) {
            return response()->json(['error' => 'Missing X-Terminal-MAC header'], 400);
        }

        // HMI sends comma-separated MACs for all active interfaces;
        // match if any one corresponds to a registered terminal
        $macs = array_map('trim', explode(',', $macHeader));
        $terminal = Terminal::whereIn('mac_address', $macs)->first();

        if (!$terminal) {
            return response()->json(['error' => 'Terminal not registered'], 403);
        }

        $request->attributes->set('terminal', $terminal);

        // Record IP address from header (for logging/diagnostics)
        if ($ip = $request->header('X-Terminal-IP')) {
            $request->attributes->set('terminal_ip', $ip);
        }

        return $next($request);
    }
}
