<?php

namespace App\Http\Middleware;

use App\Services\Care\DeviceService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateCareDevice
{
    public function __construct(
        protected DeviceService $devices,
    ) {}

    public function handle(Request $request, Closure $next, ?string $type = null): Response
    {
        $token = $this->extractToken($request);

        abort_unless(is_string($token) && $token !== '', 401, 'Device token required.');

        $device = $this->devices->findByToken($token);
        abort_unless($device, 401, 'Invalid device token.');

        if ($type !== null && $type !== '' && $device->type !== $type) {
            abort(403, 'Device type mismatch.');
        }

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

        return $next($request);
    }

    protected function extractToken(Request $request): ?string
    {
        $routeToken = $request->route('token');
        if (is_string($routeToken) && $routeToken !== '') {
            return $routeToken;
        }

        $header = $request->header('X-Care-Device-Token');
        if (is_string($header) && $header !== '') {
            return $header;
        }

        // Compatibility with Frontdesk-style header.
        $legacy = $request->header('X-Device-Token');
        if (is_string($legacy) && $legacy !== '') {
            return $legacy;
        }

        $bearer = $request->bearerToken();
        if (is_string($bearer) && $bearer !== '') {
            return $bearer;
        }

        $input = $request->input('token');

        return is_string($input) && $input !== '' ? $input : null;
    }
}
