<?php

namespace App\Http\Middleware;

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

/**
 * Authenticates sync push/pull requests using a device token issued at handshake.
 * The resolved device (and therefore its company_id) is attached to the request
 * so downstream code can scope every operation to that single company.
 */
class SyncDeviceAuth
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken() ?: $request->header('X-Sync-Token');

        if (!$token) {
            return response()->json(['status' => 0, 'message' => 'Missing device token'], 401);
        }

        $device = DB::table('sync_devices')->where('token', $token)->first();

        if (!$device) {
            return response()->json(['status' => 0, 'message' => 'Invalid device token'], 401);
        }

        if (!$device->company_id) {
            return response()->json(['status' => 0, 'message' => 'Device not bound to a company'], 403);
        }

        $request->attributes->set('sync_device', $device);

        return $next($request);
    }
}
