<?php

namespace App\Http\Middleware;

use App\Models\ShowroomSession;
use App\Services\Showroom\ShowroomPermissionService;
use Closure;
use Illuminate\Http\Request;

class ShowroomSessionMiddleware
{
    public function __construct(private readonly ShowroomPermissionService $permissionService)
    {
    }

    public function handle(Request $request, Closure $next, ...$abilities)
    {
        $token = (string) $request->bearerToken();
        if ($token === '') {
            return response()->json(['message' => 'Unauthenticated showroom session.'], 401);
        }

        $session = ShowroomSession::with('admin.role')
            ->where('token_hash', hash('sha256', $token))
            ->whereNull('revoked_at')
            ->where(function ($query) {
                $query->whereNull('expires_at')->orWhere('expires_at', '>', now());
            })
            ->first();

        if (! $session || ! $session->admin) {
            return response()->json(['message' => 'Invalid showroom session.'], 401);
        }

        if ($abilities && ! $this->permissionService->can($session->admin, $abilities)) {
            return response()->json(['message' => 'Showroom permission denied.'], 403);
        }

        $session->forceFill(['last_used_at' => now()])->save();
        $request->attributes->set('showroom_session', $session);
        $request->attributes->set('showroom_admin', $session->admin);
        $request->attributes->set('showroom_device', $session->device);

        return $next($request);
    }
}
